I have a PNG watermark image with transparent background. But randomly it generates a white background instead of staying transparent.
// Watermark
$watermark = imagecreatefrompng($docRoot . '/images/misc/watermark.png');
list($mwidth, $mheight) = getimagesize开发者_C百科($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);
Solution is to add:
imagealphablending($dst, true);
imagesavealpha($dst, true);
Complete code:
// 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,
Save $dst
with an alpha channel, not $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);
I had the same issue, but for me to get it to work I commented out these two lines from my code:
imagesavealpha($image_1, true);
imagesavealpha($image_2, true);
so my code looked like this:
$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);
now the two images merged and preserved the transparency, with those two lines it was generating a random white background, hope this helps others with the same issue
Try imagecopymerge instead of imagecopy
EDIT: try this code:
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);
精彩评论