Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge a png ontop of a jpg and retain transparency with php

Tags:

php

gd

I have a PNG and I'm trying to merge it on top of a JPG. With the following code

$dest = imagecreatefromjpeg("example.jpg");
$src = imagecreatefrompng("example.png");

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagealphablending($src, true);

imagecopymerge($dest, $src, $src2x, $src2y, 0, 0, $src2w, $src2h, 100);

header('Content-Type: image/png');
imagepng($dest, "user/".$imei."/".$picCount."_m");

imagedestroy($dest);
imagedestroy($src);

Results in the following

enter image description here

I also tried a suggestion from a similar question which said to use 'imagecopyresampled' isntead of 'imagecopymerge' but when I did that the santa hat didn't show up at all.

What do I need to change to make the santa hat keep it's transparency when merged?

like image 860
Philip Kirkbride Avatar asked Feb 23 '13 00:02

Philip Kirkbride


1 Answers

Solution required both using 'imagecopyresampled'. As well a removing lines 4 and 5 from the posted source code.

imagealphablending($dest, false);
imagesavealpha($dest, true);

Here is the complete working version

$dest = imagecreatefromjpeg("example.jpg");
$src = imagecreatefrompng("example.png");

imagecopyresampled($dest, $src, $src2x, $src2y, 0, 0, $src2w, $src2h, $src2w, $src2h); 

header('Content-Type: image/png');
imagejpeg($dest, "user/".$imei."/".$picCount."_m.jpeg");

imagedestroy($dest);
imagedestroy($src);

enter image description here

like image 83
Philip Kirkbride Avatar answered Nov 03 '22 21:11

Philip Kirkbride