PHP: Add a Transparent PNG to a JPEG with Opacity

风流意气都作罢 提交于 2019-12-08 03:06:17

问题


This seems to be a common question, but trying all the combinations, I have found, it still is not working for me.

My PNG watermark is transparent and I wish to overlay the original JPG with this watermark and add a 50% opacity to the watermark.

The watermark is added and the opacity created, but the transparency of the PNG is rendered as opaque white.

I have seen examples using imagecopy() but that function does not have the option to add opacity.

My code is as follows:

<?php
$file = 'orgCar.jpg';
$newfile = 'newCar.jpg';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
$tempIMG = imagecreatefromjpeg($newfile);
$wmkIMG = imagecreatefrompng('wmark.png');
imagealphablending($wmkIMG,true);

imagecopymerge($tempIMG, $wmkIMG, 755, 864, 0, 0, 465, 36, 50);

// Save the image to file and free memory
imagejpeg($tempIMG,'newWM.jpg');
imagedestroy($orgIMG);
imagedestroy($wmkIMG);

echo '<h3>Testing of Watermarking</h3>';
echo '<div>';
echo '<img width="160" src="orgCar.jpg" title="original" alt"" />';
echo '<img width="160" src="newCar.jpg" title="copy" alt"" />';
echo '<img width="240" src="wmark.png" title="watermark" alt"" /><br>';
echo '<img width="640" src="newWM.jpg" title="New with Watermark" alt"" />';
echo '</div>';
?>

If there is a simple answer, I have overlooked, then I would be very grateful, if someone could point me to it.


回答1:


The problem is that amount of transparency that you pass to imagecopymerge() is used instead of the image alpha channel, not added to it.

You have two options:

1) Modify the PNG so it includes the 50% opacity and then use imagecopy() (I tested it and works fine). Remember that true-color PNG's can use use a full alpha channel so you can include semi-transparency in the image.

2) use a workaround like the one described here:

imagecopymerge_alpha



来源:https://stackoverflow.com/questions/9656135/php-add-a-transparent-png-to-a-jpeg-with-opacity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!