在将图像保存到ftp服务器之前,我正在尝试使用imagecopyresampled
裁剪图像。
我的php是:
function image_resizing($image, $type, $ext, $quality, $file_name) {
strtolower($ext);
list($src_width, $src_height) = getimagesize($image);
switch($ext) {
case 'gif':
$image_create = 'imagecreatefromgif';
break;
case 'png':
$image_create = 'imagecreatefrompng';
break;
default:
$image_create = 'imagecreatefromjpeg';
break;
}
$temp_img = $image_create($image);
if($type == 'wide') {
$width = 1920;
$height = 2160;
} else if($type == 'content') {
$height = 600;
$width = 400;
}
$src_x = ($src_width - $width) / 2;
$src_y = ($src_height - $height) / 2;
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled ($new_image, $temp_img, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height);
$image_dest = '';
imagejpeg($new_image, $file_name, $quality);
}
但不知怎么的,我的裁剪区域周围总是有黑色的空间,或者在新图像中是全黑的(在较小的图像中)。据我所见,src/dest坐标是正确的。
图像:
http://www.strongleaf.nl/images/website_images/content-images/image-test-image-imagecopyresampled.jpg
http://www.strongleaf.nl/images/website_images/wide-images/image-test-image-imagecopyresampled.jpg
如果原始图像更大,我认为pb是imagecopy重采样的最后两个参数在原始图像之外划定了一个矩形。你能试试吗:
imagecopyresampled ($new_image, $temp_img, 0, 0, $src_x, $src_y, $width, $height, $width, $height);
我看到了一些问题:
1) 您应该将imagecopy重采样更改为(注意最后两个参数)
imagecopyresampled ($new_image, $temp_img, 0, 0, $src_x, $src_y, $width, $height, $width, $height);
2) 你应该有
$ext = strtolower($ext);
3) $width,$height将为零,以防将错误的$type传递到函数中
但你仍然无法避免图像周围的黑色空间,这些图像的比例与1920x2160或400x600不同,如果它们在任何维度上都较小的话。
我建议你不要为GD烦恼。用Imagick代替。
您可以在Imagick中调用::cropthumbnailimage,它将解决所有维度问题。我开始使用Imagick的主要原因是GD库的内存使用率非常高。