[英]GD: Making white background for PNG transparent
我有一个透明背景的PNG水印图像。 但是随机会产生白色背景,而不是保持透明。
// Watermark
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize($docRoot . '/images/misc/watermark.png');
// Combinde watermark image with image already generated in $dst
imagecopy($dst, $watermark, $tnWidth-$mwidth-5, $tnHeight-$mheight-5, 0, 0, $mwidth, $mheight);
解决方法是添加:
imagealphablending($dst, true);
imagesavealpha($dst, true);
完整的代码:
// Watermark
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize($docRoot . '/images/misc/watermark.png');
imagealphablending($dst, true);
imagesavealpha($dst, true);
// Combinde watermark image with image already generated in $dst
imagecopy($dst, $watermark, $tnWidth-$mwidth-5, $tnHeight-$mheight-5, 0, 0, $mwidth,
尝试使用imagecopymerge而不是imagecopy
编辑:尝试此代码:
header('Content-type: image/jpeg');
$dst = imagecreatefromjpeg($image_path);
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize($docRoot . '/images/misc/watermark.png');
imagecopymerge($dst, $watermark, $tnWidth-$mwidth-5, $tnHeight-$mheight-5, 0, 0, $mwidth, $mheight, 100);
imagejpeg($dst,'',90);
imagedestroy($dst);
使用alpha通道保存$dst
,而不是$watermark
。
// Watermark
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize($docRoot . '/images/misc/watermark.png');
imagealphablending($dst, false);
imagesavealpha($dst, true);
// Combinde watermark image with image already generated in $dst
imagecopy($dst, $watermark, $tnWidth-$mwidth-5, $tnHeight-$mheight-5, 0, 0, $mwidth, $mheight);
我遇到了同样的问题,但为了使其正常工作,我从代码中注释了这两行:
imagesavealpha($image_1, true);
imagesavealpha($image_2, true);
所以我的代码看起来像这样:
$image_1 = imagecreatefrompng("example26_".$acct.".png");
$image_2 = imagecreatefrompng('example27.png');
imagealphablending($image_1, true);
imagealphablending($image_2, true);
//imagesavealpha($image_1, true);
//imagesavealpha($image_2, true);
imagecopy($image_1, $image_2, 0, 0, 0, 0, 1350, 250);
header("Content-Type: image/png");
imagepng($image_1);
现在,两张图片合并并保留了透明度,并使用这两行生成了随机的白色背景,希望这对其他遇到相同问题的人有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.