php缩小png图片不损失透明色的实例代码

发布时间:2020-11-24编辑:脚本学堂
分享一例php代码,当缩小png图片时,不地损失透明色,学习下php 缩小png图片的方法,很实用的一段代码,有需要的朋友参考下。

说明:
png图片如果带了透明色按照jpg的方式来缩小,就会造成透明色损失。
本节介绍下缩小png图片,仍可保存透明色的方法。

主要使用gd库的两个方法:
 

复制代码 代码示例:
imagecolorallocatealpha //分配颜色 + alpha
imagesavealpha //设置在保存 png 图像时保存完整的 alpha 通道信息

完整代码:
 

复制代码 代码示例:
<?php
//获取源图gd图像标识符
$srcImg = imagecreatefrompng('./src.png');
$srcWidth = imagesx($srcImg);
$srcHeight = imagesy($srcImg);
//创建新图 www.jb200.com
$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');