Combine images using PHP

May 24, 2014 | Last tested: May 2015 | 931 views | Comments

Images can be combined in PHP, either imagecopy() or imagecopymerge() can perform the merging process of images with PHP, just to name a few.

The only difference of those mentioned functions is that with imagecopymerge(), it has an extra parameter at the end called pct (percentage) where the images will be merged according to it's value. The pct value can range from 0 to 100. No action is taken if pct = 0, and it will identically perform as imagecopy() for pallete images if it has a value of 100.

For example.

Permission to be used on this tutorial was granted for the following images.

  1. Foreground image. From this website. (This is manually re-sized.)
  2. Background image. From this website. (No manual re-sizing was made.)


Merge two JPG images using imagecopy().

//set the source image (foreground)
$sourceImage = 'create-a-halloween-mummy-icon-in-illustrator.jpg';

//set the destination image (background)
$destImage = 'lost-in-the-dark-photo-manipulation.jpg';

//get the size of the source image, needed for imagecopy()
list($srcWidth, $srcHeight) = getimagesize($sourceImage);

//create a new image from the source image
$src = imagecreatefromjpeg($sourceImage);

//create a new image from the destination image
$dest = imagecreatefromjpeg($destImage);

//set the x and y positions of the source image on top of the destination image
$src_xPosition = 10; //10 pixels from the left
$src_yPosition = 10; //10 pixels from the top

//set the x and y positions of the source image to be copied to the destination image
$src_cropXposition = 0; //do not crop on the side
$src_cropYposition = 0; //do not crop at the top

//merge the source and destination images

//output the merged images to a file

//destroy the source image

//destroy the destination image


Please mouse over here to view the image.