PHP裁剪图片且保留背景透明

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); // 销毁资源对象 - 句柄

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值