保留PNG透明度,同时调整大小,没有黑色背景


Preserve PNG transparency while resizing with out the black background

我有一个处理图像处理的小类。

我使用以下命令来调整图像的大小

$this->image = imagecreatefrompng($filename);
....
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
...
$this->image = $new_image; 
imagepng($this->image,$filename)) { return true; }

但是调整后的图片没有保持透明度,反而出现了黑色,我该如何保持透明度

更新

之后,使用@Manuel的代码,黑色部分已经减少,但仍然是黑色背景仍然存在。源图像和结果图像为

源,子对应的

main http://www.freeimagehosting.net/newuploads/820a0.png sub http://www.freeimagehosting.net/newuploads/30526.png

5月8日发布在imagecopyresampled手册页上的最新评论告诉你如何做到这一点。

imagecolortransparent($new_image, imagecolorallocatealpha($new_image, 0, 0, 0, 127));
imagealphablending($new_image, false);
imagesavealpha($new_image, true);

在创建$new_image后把它放在右边

imagecopyresampled(...)前加上这个

// preserve transparency
imagecolortransparent($new_image , imagecolorallocatealpha($new_image , 0, 0, 0, 127));
imagealphablending($new_image , false);
imagesavealpha($new_image , true);