Search code examples
phpimage-processingphp-gd

Merging two PNG images with PHP imagecopy does not work


Here a simple example that I cannot make it work.

I create 2 simple images of 2x2px with a dot in different coordinates and I try to merge it using imagecopy. The second image ($stamp) is created properly with a transparent background. As result, I expect to see two white dots in the resulting image (result.png) but it is not the case.

I have try several combination of functions with no result.

What am I missing here?

<?php

// create source image
$src = imagecreatetruecolor(2, 2);
$white = imagecolorallocate($src, 255, 255, 255);
$black = imagecolorallocate($src, 0, 0, 0);

imagesetpixel($src, 0, 0, $white);
imagepng($src, 'src.png');

// create stamp image
$stamp = imagecreatetruecolor(2, 2);
imagecolortransparent($stamp, $black);
imagesetpixel($stamp, 1, 1, $white);
imagepng($stamp, 'stamp.png');

imagedestroy($src);
imagedestroy($stamp);

// merging images
$src = imagecreatefrompng('src.png');
$stamp = imagecreatefrompng('stamp.png');

imagealphablending($src, true);
imagesavealpha($src, true);

imagecopy($src, $stamp, 0, 0, 0, 0, 2, 2);
imagepng($src, 'result.png');

imagedestroy($src);

Solution

  • Try something like this.

    // create stamp image
    $stamp = imagecreatetruecolor(2, 2);
    imagesavealpha($stamp, true);
    $transparent_colour = imagecolorallocatealpha($stamp, 0, 0, 0, 127);
    imagefill($stamp, 0, 0, $transparent_colour);
    
    $white = imagecolorallocate($stamp, 255, 255, 255);
    
    imagesetpixel($stamp, 1, 1, $white);
    imagepng($stamp, 'stamp.png');
    

    The only difference is that you use imagesavealpha to allow transparency when creating the stamp and src images, then fill with transparent color using imagecolorallocatealpha.

    After that, add your white pixel to one and your black pixel to the other as before. Then combine them.