Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP GD library, turn 2 images into 1 side by side [closed]

Tags:

php

image

gd

I want to take two images and turn them into one side by side (not overlapping). An example of what I'd want to do is something like a before and after picture (both images would have the same height with a different width). Any example code on how to accomplish with with the PHP GD image library would be greatly appreciated. Thanks!

like image 622
Graham Avatar asked Sep 03 '14 04:09

Graham


1 Answers

<?php

$img1_path = 'images_1.png';
$img2_path = 'images_2.png';

list($img1_width, $img1_height) = getimagesize($img1_path);
list($img2_width, $img2_height) = getimagesize($img2_path);

$merged_width  = $img1_width + $img2_width;
//get highest
$merged_height = $img1_height > $img2_height ? $img1_height : $img2_height;

$merged_image = imagecreatetruecolor($merged_width, $merged_height);

imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);

$img1 = imagecreatefrompng($img1_path);
$img2 = imagecreatefrompng($img2_path);

imagecopy($merged_image, $img1, 0, 0, 0, 0, $img1_width, $img1_height);
//place at right side of $img1
imagecopy($merged_image, $img2, $img1_width, 0, 0, 0, $img2_width, $img2_height);

//save file or output to broswer
$SAVE_AS_FILE = TRUE;
if( $SAVE_AS_FILE ){
    $save_path = "your target path";
    imagepng($merged_image,$save_path);
}else{
    header('Content-Type: image/png');
    imagepng($merged_image);
}

//release memory
imagedestroy($merged_image);

?>

try it

like image 155
Parfait Avatar answered Sep 24 '22 02:09

Parfait