您的位置:首页 > 编程语言 > PHP开发

php缩小png图片不损失透明色的解决方法

2013-12-25 00:00 781 查看
主要是利用gd库的两个方法:
imagecolorallocatealpha //分配颜色 + alpha

imagesavealpha //设置在保存 png 图像时保存完整的 alpha 通道信息


代码示例:

//获取源图gd图像标识符
$srcImg = imagecreatefrompng('./src.png');
$srcWidth = imagesx($srcImg);
$srcHeight = imagesy($srcImg);

//创建新图
$newWidth = round($srcWidth / 2);
$newHeight = round($srcHeight / 2);
$newImg = imagecreatetruecolor($newWidth, $newHeight);
//分配颜色 + alpha,将颜色填充到新图上
$alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
imagefill($newImg, 0, 0, $alpha);

//将源图拷贝到新图上,并设置在保存 PNG 图像时保存完整的 alpha 通道信息
imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
imagesavealpha($newImg, true);
imagepng($newImg, './dst.png');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: