Image transparency and alpha when merging images with PHP
gd, image, image-processing, mask, php
Solution
Please note that your frame has white edges and if you sill want the windows to be wite you need to crop it and remove the `imagecolortransparent` added below if not you can use this
$imgl = "thumb/pattern.png";
$img2 = "thumb/frame.png";
$dest = imagecreatefrompng($imgl);
$src = imagecreatefrompng($img2);
imagecolortransparent($src, imagecolorat($src, 0, 0));
$src_x = imagesx($src);
$src_y = imagesy($src);
imagecopymerge($dest, $src, 0, 0, 0, 0, $src_x, $src_y, 100);
// Output and free from memory
header('Content-Type: image/png');
imagegif($dest);
imagedestroy($dest);
imagedestroy($src);
Output
You can also have
$imgl = "thumb/pattern.png";
$img2 = "thumb/frame.png";
$dest = imagecreatefrompng($imgl);
$src = imagecreatefrompng($img2);
$src_x = imagesx($src);
$src_y = imagesy($src);
$srcNew = imagecreatetruecolor($src_x, $src_y);
ImageColorTransparent($srcNew, imageColorAllocate($srcNew, 0, 0, 0));
imagecopy($srcNew, $src, 70, 50, 78, 60, 473, 293);
imagecopymerge($dest, $srcNew, 0, 0, 0, 0, $src_x, $src_y, 100);
header('Content-Type: image/png');
imagegif($dest);
imagedestroy($dest);
imagedestroy($src);
Output
Problem
So I found some code on PHP Doc, and edited it slightly to merge two images I have. The image is then saved in a folder on the server. However there is a slight problem and I am unable to figure out why it is happening. Firstly my code: ``` $glassurl = $_GET['GlassImg']; $frameurl = $_GET['FrameImg']; $filename = (int)date("H:i:s"); $src = imagecreatefromgif($frameurl); $dest = imagecreatefromjpeg($glassurl); imagecolortransparent($src, imagecolorat($src, 0, 0)); imagealphablending($dest, false); imagesavealpha($dest, true); imagealphablending($src, false); imagesavealpha($src, true); $src_x = imagesx($src); $src_y = imagesy($src); imagecopymerge($dest, $src, 0, 0, 0, 0, $src_x, $src_y, 100); // Output and free from memory imagepng($dest, 'uploads/imagetest.png'); imagegif($dest); imagedestroy($dest); imagedestroy($src ); ``` Secondly some information about the images: - Both Images are exactly the same size - The 'pattern' image is just a block colour/pattern - The frame image has transparent parts within the frame (to allow pattern to show through) - The area around the frame is white to hise the excess pattern I was hoping that when I overlayed the frame onto the pattern because of these parts that it would produce a window frame, with the glass pattern inside, and the white would hide the remaining patten. To illustrate I have provided the images. and what happens. Pattern: Frame: Result: As you can see it doesn't result in what I expected. Can anyone please tell me where I am going wrong? I want to overlay the frame onto the pattern, keeping the transparent center and using the excess white to cover the rest of the patter. Any help is greatly appreciated.