Merge two PNG images with the PHP GD library

Does anyone have a script that can combine two PNG images?

Under the following conditions:

  • Both images have transparent areas.
  • The second image should have an opacity of 50% (overlays on top of the first image)

Here is what I tried to do, but no luck:

<?php function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){ $cut = imagecreatetruecolor($src_w, $src_h); imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h); imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h); imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct); } $image1 = imagecreatefrompng('a.png'); //300 x 300 $image2 = imagecreatefrompng('b.png'); //150 x 150 $merged_image = imagecreatetruecolor(300, 300); imagealphablending($merged_image, false); imagesavealpha($merged_image, true); imagecopy($merged_image, $image1, 0, 0, 0, 0, 300, 300); imagecopymerge_alpha($merged_image, $image2, 0, 0, 0, 0, 150, 150, 50); header('Content-Type: image/png'); imagepng($merged_image); ?> 

Edit:

  • The first image (left) and the second image (right)

enter image description hereenter image description here

  • Here's how it should be (left) and the result of my code (right)

enter image description hereenter image description here

  • Solution Result Proposed by dqhendricks

enter image description here

+7
source share
2 answers
 $image1 = imagecreatefrompng('a.png'); //300 x 300 $image2 = imagecreatefrompng('b.png'); //150 x 150 imagecopymerge($image1, $image2, 0, 0, 75, 75, 150, 150, 50); 

That should be all you need. $ image1 should contain a merged image in which image2 was overlaid with an opacity of 50%. the last argument is the alpha of the merged copy.

http://php.net/manual/en/function.imagecopymerge.php

+8
source
 $merged_image = imagecreatetruecolor(300, 300); imagealphablending($merged_image, false); imagesavealpha($merged_image, true); imagecopy($merged_image, $image1, 0, 0, 0, 0, 300, 300); // after first time of "imagecopy" change "imagealphablending" imagealphablending($merged_image, **true**); imagecopy($merged_image, $image2, 0, 0, 0, 0, 300, 300); 
0
source

All Articles