Skip to content
PHP Logo

What are the best practices for delivering multiple images in PHP using imagegif?

When delivering multiple images in PHP using imagegif, it is best practice to create a single image resource and then append each individual image to it before outputting the final image. This can be achieved by creating a blank canvas with imagecreatetruecolor(), copying each image onto the canvas with imagecopy() or imagecopymerge(), and then outputting the final image with imagegif().

php
// Create a blank canvas to hold the final image
$finalImage = imagecreatetruecolor($width, $height);

// Loop through each individual image and append it to the final image
foreach ($images as $img) {
    $tempImage = imagecreatefromgif($img);
    imagecopy($finalImage, $tempImage, $x, $y, 0, 0, imagesx($tempImage), imagesy($tempImage));
    $x += imagesx($tempImage); // Update x position for next image
}

// Output the final image as a GIF
header('Content-type: image/gif');
imagegif($finalImage);

// Free up memory by destroying the image resources
imagedestroy($finalImage);