答案 0 :(得分:3)
答案 1 :(得分:1)
尝试此功能....
<?php
function CropImg($img_dst, $img_src, $dst_width = 300, $dst_height = 180){
$ext = pathinfo($img_src, PATHINFO_EXTENSION);
if($ext != 'jpg' and $ext != 'jpeg'){
$image = imagecreatefrompng($img_src);
}else{
$image = imagecreatefromjpeg($img_src);
}
$filename = $img_dst;
$thumb_width = $dst_width;
$thumb_height = $dst_height;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
if($ext == 'png'){
imagealphablending($thumb, false);
$white = imagecolorallocatealpha($thumb, 0, 0, 0, 127); //FOR WHITE BACKGROUND
imagefilledrectangle($thumb,0,0,$thumb_width,$thumb_height,$white);
imagesavealpha($thumb, true);
}
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
if($ext == 'png'){
imagepng($thumb, $filename);
}else{
imagejpeg($thumb, $filename, 80);
}
return true;
}
CropImg("photo.png", "result.png", 300, 180);
?>