Right, so I set out to build a function in PHP that could merge two images together whilst preserving the transparent background of the PNG files - which I successfully accomplished - using the code below,
function imageCreateTransparent($x, $y) {
$imageOut = imagecreatetruecolor($x, $y);
$colourBlack = imagecolorallocate($imageOut, 0, 0, 0);
imagecolortransparent($imageOut, $colourBlack);
return $imageOut;
}
function mergePreregWthQR($preRegDir, $qrDir){
$top_file = $preRegDir;
$bottom_file = $qrDir;
$top = imagecreatefrompng($top_file);
$bottom = imagecreatefrompng($bottom_file);
// get current width/height
list($top_width, $top_height) = getimagesize($top_file);
list($bottom_width, $bottom_height) = getimagesize($bottom_file);
// compute new width/height
$new_width = ($top_width > $bottom_width) ? $top_width : $bottom_width;
$new_height = $top_height + $bottom_height;
// create new image and merge
$new = imageCreateTransparent($new_width,$new_height);
imagecopy($new, $bottom, 0, $top_height+1, 0, 0, $bottom_width, $bottom_height);
imagecopy($new, $top, 0, 0, 0, 0, $top_width, $top_height);
$filename = "merged_file.png";
// save to file
imagepng($new, $filename);
}
mergePreregWthQR("file.png", "qr.png");
This managed to merge the two images and keep the transparent background, the only problem was that any black coloured pixels in the merged images turned transparent and the result of this merge is shown here > merged image
the top image is the jellyfish image, the bottom is a QR code, which can only be seen when the image is placed on any background other than white. So what I am pretty sure is happening, is that imagecolortransparent($imageOut, $colourBlack); turns every black pixel in the newly created merged_file.png to transparent. I tested the theory by altering imageCreateTransparent($x, $y) slightly to what is shown below,
function imageCreateTransparent($x, $y) {
$imageOut = imagecreatetruecolor($x, $y);
$colourBlack = imagecolorallocate($imageOut, 55, 55, 55);
imagefill ( $imageOut, 0, 0, $colourBlack );
imagecolortransparent($imageOut, $colourBlack);
return $imageOut;
}
so in this function I am filling the entire image with the colour (55, 55, 55) then setting this colour to transparent in my imagecolortransparent() function. This does the trick, and my QR code is shown as it should be. The only problem is that I see this as a quick and dirty hack and if anyone has the colour (55, 55, 55) in an uploaded image it will turn transparent ? So I am curious to know what another solution would be? Thanks.