PHP裁剪图片用到的函数是:
imagecopyresampled( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
dst_image
目标图象资源。
src_image
源图象资源。
dst_x
目标 X 坐标点。
dst_y
目标 Y 坐标点。
src_x
源的 X 坐标点。
src_y
源的 Y 坐标点。
dst_w
目标宽度。
dst_h
目标高度。
src_w
源图象的宽度。
src_h
源图象的高度。
注意:src_w,src_h文档指的是源图像的宽高,但是实际调用传的是目标宽高,不然生成的图像会变形。
例如:需要裁剪图像的开始坐标100,150,宽高300,500,则调用:
imagecopyresampled(resource $dst_image , resource $src_image, 0, 0, 100, 150, 300, 500, 300, 500)
代码:
$width_save = 300;
$height_save = 500;
$img_source = imagecreatefrompng('1.png');
$img_target = ImageCreateTrueColor($width_save, $height_save);
imagecopyresampled($img_target, $img_source, 0, 0, 100, 150, $width_save, $height_save, $width_save, $height_save);
Imagepng($img_target, 'D://target.png'); // 保存裁剪后的图片到本地
ImageDestroy($img_source); // 销毁资源对象 - 句柄
ImageDestroy($img_target); // 销毁资源对象 - 句柄
如果裁剪的图片是透明背景,则代码:
$width_save = 300;
$height_save = 500;
$img_source = imagecreatefrompng('1.png');
imagesavealpha($img_source, true); // 保留源图片透明度
$img_target = ImageCreateTrueColor($width_save, $height_save);
imagealphablending($img_target, false); // 不合并图片颜色
imagesavealpha($img_target, true); // 保留目标图片透明度
imagecopyresampled($img_target, $img_source, 0, 0, 100, 150, $width_save, $height_save, $width_save, $height_save);
Imagepng($img_target, 'D://target.png'); // 保存裁剪后的图片到本地
ImageDestroy($img_source); // 销毁资源对象 - 句柄
ImageDestroy($img_target); // 销毁资源对象 - 句柄