Skip to content
PHP Logo

How can the imagecopy() function be used to achieve the goal of copying and combining multiple images in PHP, and what are the benefits of using this function over pixel-by-pixel manipulation?

To copy and combine multiple images in PHP, you can use the imagecopy() function. This function allows you to copy a portion of one image onto another image, effectively combining them. Using imagecopy() is more efficient and easier than manipulating pixels individually, as it handles the copying and positioning of images automatically.

php
// Create a blank image to hold the combined images
$combinedImage = imagecreatetruecolor($width, $height);

// Copy the first image onto the combined image
imagecopy($combinedImage, $image1, 0, 0, 0, 0, $width1, $height1);

// Copy the second image onto the combined image
imagecopy($combinedImage, $image2, $width1, 0, 0, 0, $width2, $height2);

// Output or save the combined image
imagepng($combinedImage, 'combined_image.png');

// Free up memory
imagedestroy($combinedImage);