Transparent PNG over JPG in PHP

ekstrakt picture ekstrakt · Nov 2, 2011 · Viewed 8.1k times · Source

What seems to be simple, isn't :(

I'm trying to add something like a watermark (transparent png) on an image (jpg). This is the code I'm using:

$width = 800; 
$height = 600; 
$bottom_image = imagecreatefromjpeg("portrait1.jpg"); 
$top_image = imagecreatefrompng("man2.png"); 
imagesavealpha($top_image, true); 
imagealphablending($top_image, true); 
imagecopy($bottom_image, $top_image, 200, 200, 0, 0, $width, $height); 
header('Content-type: image/png');
imagepng($bottom_image);

When I merge the images, the png is positioned at the right place, everythig above and left of it is good (jpg is copied), but everything else is black.

I've tried setting imagesavealpha and imagealphablending to false, there wasn't any difference.

You can see the resulting image at http://ekstrakt.selfip.com/photobomb/image.php

I've searched around the net, I can't find a solution.

Any help is appreciated.

Answer

Niet the Dark Absol picture Niet the Dark Absol · Nov 2, 2011

Your $width and $height should be the dimensions of the watermark, not of the photo. What you're telling it to do is copy the watermark with a much bigger size than it is. When it reads part of an image that doesn't exist (coordinates out of bounds) the result is opaque black, giving the result you see.