Home  >  Article  >  php教程  >  php缩小png图片不损失透明色的解决方法

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

WBOY
WBOYOriginal
2016-06-06 20:26:001254browse

png图片如果带了透明色按照jpg的方式来缩小,就会造成透明色损失。那么如何处理才能保存透明色呢?下面的代码就可以解决这个问题

主要是利用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');

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn