2

i need to concatenate images in php (two or more), both vertically and horizontally. What's the fastest way to do that?

obs: i don't want to use non-native libraries

another doubts. will the resulting image have the sum of the images sizes or could it be significantly bigger?

thanks (:

Hugo Mota
  • 11,200
  • 9
  • 42
  • 60

1 Answers1

3
$newWidth = $w1 + $w2;
$newHeight = $h1 + $h2;
$newImage = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled($newImage, $image1, 0, 0, 0, 0, $w1, $h1, $w1, $h1);
imagecopyresampled($newImage, $image2, $w1, 0, 0, 0, $w2, $h2, $w2, $h2);

Now i did just code this in stack overflows editor and it is untested, but that should use all native libraries and probably be the fastest. Just copies and resamples the image1 into the first half (width wise) and then copies the second image into the second half (width wise), if you wanted to do it by stacking on height, it would just be changing where the dest_h is. Here is some info... http://php.net/manual/en/function.imagecopyresampled.php

oh BTW, that was for saving an image. That is what i am assuming your doing. Else the answer about stacking 2 images next to eachother with tags would be the fastest.

As far as the resulting image, remember. If they are laid horizontally, then the width would be $w1 + $w2 and the height would be math.max($h1, $h2) and opposite if the images are stacked vertically

ThePrimeagen
  • 4,462
  • 4
  • 31
  • 44
  • Generally, that works for solid images. For transparent ones, you should provide more code. – Wh1T3h4Ck5 Apr 26 '11 at 17:40
  • that is really helpful! won't it be a problem if $image1 is jpg and $image2 is png (for instance)? – Hugo Mota Apr 26 '11 at 17:41
  • 2
    @hugo, it depends of what kind of transparency you have inside original source (image) or what's type of original image (gif, png8, png32, etc). Than you should care about alpha-colors. This example describes [how to get transparent rounded corners on image](http://stackoverflow.com/questions/5766865/rounded-transparent-smooth-corners-using-imagecopyresampled-php-gd/5767092#5767092), and returns PNG 32-bit image. Also, that depends of what output you expect as transparent image (gif or png, if png what kind of png 8, 24, 32). – Wh1T3h4Ck5 Apr 26 '11 at 17:48