Monday, August 29, 2011

jpeg and png image merge using php

Sina Salek@php.net
09-Aug-2009 08:26
I've just checked PHP's issue tracker and a core developer says that this function was never meant to support alpha channel! and they refused to commit the provided patch! so ridicules
Anyway i tried rodrigo's workaround and it worked quite well, thanks rodrigo for sharing it.
I came up with another idea which is much faster than his solution, (it may need a little bit more memory)

Hope it helps someone.

$TFrontObj=imagecreatefrompng($NTFrontImg);
imagealphablending($TFrontObj, false);
imagesavealpha($TFrontObj, true);
$this->imagecopymerge_alpha($TFrontObj,$NewImg,$NImgPos[0],$NImgPos[1],0,0,$NImgSize[0],$NImgSize[1],90);

imagepng($TFrontObj,$NTFrontImg);
imagepng($TBackObj,$NTBackImg);
# Save the image to a file
# Output straight to the browser.
imagedestroy($TFrontObj);
imagedestroy($TBackObj);
imagedestroy($NewImg);$TImgCheck=true; //exit;


/**
* PNG ALPHA CHANNEL SUPPORT for imagecopymerge();
* by Sina Salek
*
* Bugfix by Ralph Voigt (bug which causes it
* to work only for $src_x = $src_y = 0.
* Also, inverting opacity is not necessary.)
* 08-JAN-2011
*
**/
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
// creating a cut resource
$cut = imagecreatetruecolor($src_w, $src_h);

// copying relevant section from background to the cut resource
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

// copying relevant section from watermark to the cut resource
imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

// insert cut resource to destination image
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}

?>
by