当我用php上传png图像时,图像的背景色被设置为黑色。
我试着将它设置为透明背景,但它不起作用。
这是我的代码:
if( $image_type == IMAGETYPE_PNG )
{
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagealphablending($dst_r, false);
imagesavealpha($dst_r, true);
imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));
imagecopyresampled($dst_r, $this->image, 0, 0, $targ_x, $targ_y, $targ_w, $targ_h, $targ_w, $targ_h);
imagepng($dst_r,$filename, 9);
}
编辑:
我以为我已经解决了这个问题,但是我错了:
$targ_w_thumb = $targ_h_thumb = 220;
if($image_type == IMAGETYPE_PNG)
{
$dst_r = ImageCreateTrueColor($targ_w_thumb, $targ_h_thumb);
imagealphablending($dst_r, false);
imagesavealpha($dst_r, true);
imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));
imagecopyresampled($dst_r, $this->image, 0, 0, $targ_x, $targ_y, $targ_w_thumb, $targ_h_thumb, $targ_w, $targ_h);
imagepng($dst_r,$filename, 9);
}
imagecreatetruecolor()
创建一个不透明的黑色填充的图像。除非你先用透明填充你的新图像,否则黑色稍后就会显现出来。
所有你需要的是一个透明颜色的imagefill()
-即黑色,像这样:
imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127)); // transparency values range from 0 to 127
应用到你的代码,这应该工作:
if( $image_type == IMAGETYPE_PNG )
{
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagealphablending($dst_r, false);
imagesavealpha($dst_r, true);
// Paint the watermark image with a transparent color to remove the default opaque black.
// If we don't do this the black shows through later colours.
imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));
imagecopyresampled($dst_r, $this->image, 0, 0, $targ_x, $targ_y, $targ_w, $targ_h, $targ_w, $targ_h);
imagepng($dst_r,$filename, 9);
}
我不知道为什么,但是当我添加targ_w_thumb时,它的工作很好+ imagefill():
$targ_w_thumb = $targ_w_thumb = 200;
$dst_r = ImageCreateTrueColor($targ_w_thumb, $targ_h_thumb);
imagealphablending($dst_r, false);
imagesavealpha($dst_r, true);
imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));
imagecopyresampled($dst_r, $this->image, 0, 0, $targ_x, $targ_y, $targ_w_thumb, $targ_h_thumb, $targ_w, $targ_h);
imagepng($dst_r,$filename, 9);