PHP - merging images

Using PHP to merge several graphic layers into one

This page gives a practical demonstration of how to build up an image in layers using PHP and output the result. The image above has been built from three layers. The first shows Einstein at a blank blackboard. The second shows the contents of the text area box as a rendered graphic using a true type font. The third shows just Einstein on a clear background - a transparent gif. On hitting submit, the text layer is created, and sandwiched in between the other two. Both the first and third images are the same size.

You can scroll down to see the full code. This technique, or similar, is used by sites such as

Enter your text in the text box at the top of the page and click submit. You will need to add an 'enter' for new lines to work - the text area text wrap in itself won't give a new line. If the image doesn't appear, press Ctrl F5 on your keyboard to refresh your browser.


The code 

Here is the actual PHP code that does the trick

//FULL PATH TO OUTPUT FILE (the Final image)
//FULL PATH TO FIRST IMAGE (The image you are going to write on)
//FULL PATH TO THE THID IMAGE (the image you are going to put over the written on image)
//FULL PATH TO THE SECOND IMAGE (The first image with the writing placed on it)
$TextImage = '/fullpath/whatever/einstein.jpg';
$font = '/fullpath/whatever/freescript.ttf';
//*************END OF VARIABLES*******************

function Addtext ($Layer1, $Text, $TextImage, $font) {
   list($width, $height) = getimagesize($TextImage);
   $image_p = imagecreatetruecolor($width, $height);
   $image = imagecreatefromjpeg($Layer1);
   imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
   $color = imagecolorallocatealpha($image_p, 255, 255, 255, 70);
   $font_size = 40;
   imagettftext($image_p, $font_size, -4, 50, 50, $color, $font, $Text);
   if ($TextImage<>'') {
      imagejpeg ($image_p, $TextImage, 30);
   } else {
      header('Content-Type: image/jpeg');
      imagejpeg($image_p, null, 30);

function Layerstuff ($TextImage, $Layer2, $FinalLayer) {

   list($width, $height) = getimagesize($TextImage);
   $image2 = imagecreatetruecolor($width, $height); 
   $image1 = imagecreatefromjpeg($TextImage);
   $image2 = imagecreatefromgif($Layer2);
   imagecopymerge ($image1, $image2, 0,0,0,0, $width, $height, 100);

   if ($FinalLayer<>'') {
      imagejpeg ($image1, $FinalLayer, 30);
   } else {
      header('Content-Type: image/jpeg');
      imagejpeg($image1, null, 30);

$output =<<<EOF
<form method="POST" action=""><textarea cols=40 rows=10 name="Text" value=""
style="height:300px; width: 500px; background-color: transparent; color:#FFFFFF;"
<input type="submit" value="submit">


if (isset($Text))

Addtext ($Layer1, $Text, $TextImage, $font);
Layerstuff ($TextImage, $Layer2, $FinalLayer);


$output.="<br><image src=\"/URL PATH/".$FinalLayer."\"><br>";
echo $output;