How to quickly merge two images using php?

by cortez.connelly , in category: PHP General , a month ago

How to quickly merge two images using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , a month ago

@cortez.connelly 

You can quickly merge two images using PHP by using the imagecopy function provided by the GD library in PHP. Here is a simple example code snippet to merge two images:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Load the two images you want to merge
$image1 = imagecreatefrompng('image1.png');
$image2 = imagecreatefrompng('image2.png');

// Get the dimensions of the first image
$width1 = imagesx($image1);
$height1 = imagesy($image1);

// Get the dimensions of the second image
$width2 = imagesx($image2);
$height2 = imagesy($image2);

// Create a new image to merge the two images into
$mergedImage = imagecreatetruecolor($width1, $height1);

// Copy the first image onto the merged image at position (0, 0)
imagecopy($mergedImage, $image1, 0, 0, 0, 0, $width1, $height1);

// Copy the second image onto the merged image at position (0, 0)
imagecopy($mergedImage, $image2, 0, 0, 0, 0, $width2, $height2);

// Output the merged image
header('Content-Type: image/png');
imagepng($mergedImage);

// Free up memory
imagedestroy($image1);
imagedestroy($image2);
imagedestroy($mergedImage);


In this example, we loaded two images (image1.png and image2.png), created a new image with the dimensions of the first image, copied the first image onto the merged image at position (0, 0), and then copied the second image onto the merged image at the same position. Finally, we output the merged image to the browser as a PNG image.