[英]Upload png image black background
当我使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.