PHPology is a collective of highly skilled, award winning, web gurus.
Contact Raj on 07985 467 213 or email [email protected]

Merging images side by side with PHP and GD

Previously I wrote a script example of merging transparents PNG's side by side so here is a JPG version of the code.

<?php 
ini_set('display_errors', 1);
ini_set('memory_limit', -1);

//where are the images stored
$src_dir = './';  

//because our images were named as number i.e. 0.png, 1.png, 2.png, 3.png etc etc, using the range()
$numbers = range(1, 10);  //we have 10 images as a sample

$dest_w = 0; 

foreach ($numbers as $key => $val)
{ 
    $src = $src_dir . $val . '.jpg';  
    $size = getimagesize($src);  

    $src_gds[$key]['img'] = imagecreatefromjpeg($src); 
    $src_gds[$key]['w'] = $size[0];  
    $src_gds[$key]['h'] = $size[1]; 
    $dest_w += $src_gds[$key]['w']; 
    $hts[] = $src_gds[$key]['h'];  
}  

$dest_h = max($hts); 

$dest_gd = imagecreatetruecolor($dest_w, $dest_h); 
         
$dest_x = 0; 

foreach ($src_gds as $gd)
{ 
    imagecopymerge($dest_gd, $gd['img'], $dest_x, 0,  0, 0, $gd['w'], $gd['h'], 99); 
    $dest_x += $gd['w']; 
    imagedestroy($gd['img']);  
}  

header ("Content-type: image/jpeg"); 
imagejpeg($dest_gd);  
imagedestroy($dest_gd);  
?>