August 10, 2011

Merge two images with php image libraries gd2 and imagick

function mergeFrontBack($img_front, $img_back, $final_output, $x, $y, $imagick=FALSE)
{

if($imagick)
{

$overlay = new Imagick($img_front);
$bg = new Imagick($img_back);
$temp_image = new Imagick();

$d = $overlay->getImageGeometry();
$w = $d[‘width’];
$h = $d[‘height’];

$bg_temp = $this->prefixToImg(‘_temp’,$bg);
$bg_copy = $this->prefixToImg(‘_copy’,$bg);

$temp_image->newImage($w, $h, new ImagickPixel(‘white’));
$temp_image->setImageFormat(‘png’);
$temp_image->writeImage($bg_temp);

// Set the colorspace to the same value
$temp_image->setImageColorspace($bg->getImageColorspace());

//Second image is put on top of the first
$temp_image->compositeImage($bg, $bg->getImageCompose(), $x, $y);

$temp_image->writeImage($bg_copy);

$final_copy = new Imagick($bg_copy);

// Set the colorspace to the same value
$final_copy->setImageColorspace($overlay->getImageColorspace() );

//Second image is put on top of the first
$final_copy->compositeImage($overlay, $overlay->getImageCompose(), 0, 0);

//new image is saved as final.jpg
$final_copy->writeImage($final_output);

if(file_exists($bg_temp))
unlink($bg_temp);

if(file_exists($bg_copy))
unlink($bg_copy);

}
else
{

$img_front = $this->getImgSrc($img_front);
$img_back = $this->getImgSrc($img_back);

$width = imagesx($img_front);
$height = imagesy($img_front);

$swidth = imagesx($img_back);
$sheight = imagesy($img_back);

$im = imagecreatetruecolor($width, $height);
//$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// Make the background transparent
imagecolortransparent($im, $black);

//imagepng($im, RELA.’test1.png’);

imagecopy ($im, $img_back , $x , $y , 0 , 0 , $width , $height );

//imagecopyresampled($im, $img_back , $x , $y , 0 , 0 , $width , $height, $swidth, $sheight );

//TRANSPARENT IMAGE CREATED SUCCESSFULLY
//imagepng($im, RELA.’test2.png’);

imagecopy ($im, $img_front , 0 , 0 , 0 , 0 , $width , $height );

imagepng($im,$final_output,0);

imagedestroy($im);

}
}

Last updated: March 19, 2014