PHP调整图像大小并保存透明PNG

时间:2014-03-11 04:28:16

标签: php png transparent

我在我的网站上有一个png图片上传脚本,我正在将大图像缩小到小尺寸,我正在使用此代码,但它失去了透明背景

$image = $tmp; // Uploaded Image
$maxImgWidth = 224;
$src = imagecreatefrompng($image);
list($width, $height) = getimagesize($image);
$newwidth = $maxImgWidth;
$newheight = ($height / $width) * $newwidth;
$newImage = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($image, true);
imagesavealpha($image, true);
imagecopyresampled($newImage, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($newImage, "../thumb/$name_after-$code.$ext", 1);
imagedestroy($src);
imagedestroy($newImage);

此代码使图片无透明度:

enter image description here

我希望透明背景如下:

enter image description here

1 个答案:

答案 0 :(得分:2)

抱歉我没有PHP经验,但在我阅读this page之后,我认为您可能需要在设置后添加透明色 保存alpha是真的

imagesavealpha($image, true);
$color = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $color);

如果仍然无法尝试imagecolorallocatealpha()之后添加此内容,

imagecolortransparent($image, $color);