因业务需要,我需要将上传的图片转换成gif图片,还需要对尺寸较大的图片的尺寸进行压缩
期间产生了一些问题:
1、png图片转换后透明色变成了黑色 (进行了透明色填充处理)
2、发现图片非透明色区域的轮廓有白边(因该是透明色填充有问题)
最后记录下成功的代码:
$filepathsrc = $destDir . $fileName;
switch($suffix) {
case 'png':
$image = imagecreatefrompng($filepathsrc);
break;
case 'jpg':
$image = imagecreatefromjpeg($filepathsrc);
break;
case 'webp':
$image = imagecreatefromwebp($filepathsrc);
break;
}
list($width, $height) = getimagesize($filepathsrc);
$fname = substr($filepathsrc,0, strrpos($filepathsrc, '.'));
$newfilename = $fname . '.gif';
if($width > self::$MAXWLIMIT || $height>self::$MAXWLIMIT) {
$newwidth = self::$MAXWLIMIT;
$newheight = self::$MAXWLIMIT;
if($width > $height) {
$newheight = round($height/$width * $newwidth);
}else{
$newwidth = round($width/$height * $newheight);
}
}else{
$newwidth = $width;
$newheight = $height;
}
$newImage = imagecreatetruecolor($newwidth, $newheight);
$color = imagecolorallocatealpha($newImage,255,255,255, 127);
imagecolortransparent($newImage, $color);
imagefill($newImage,0,0,$color);
// 在新的画布上复制调整后的图像
imagecopyresampled($newImage, $image, 0, 0, 0, 0,$newwidth, $newheight, $width, $height);
$res = imagegif($newImage, $newfilename);
if ($res) {
$filePath = $newfilename;
$extgif = 'gif';
}
imagedestroy($newImage);
imagedestroy($image);