3

I'd like to add one image to the bottom of another in php

I've this to load the images:

//load top
$top = @imagecreatefrompng($templateTop);
//load bottom
$bottom = @imagecreatefrompng($templateBottom);

Now I'd like to add them to one picture and display top and bottom together.

What way can I do this?

Thanks!

baklap
  • 2,145
  • 6
  • 28
  • 41

3 Answers3

19

Use imagecopy:

$top_file = 'image1.png';
$bottom_file = 'image2.png';

$top = imagecreatefrompng($top_file);
$bottom = imagecreatefrompng($bottom_file);

// get current width/height
list($top_width, $top_height) = getimagesize($top_file);
list($bottom_width, $bottom_height) = getimagesize($bottom_file);

// compute new width/height
$new_width = ($top_width > $bottom_width) ? $top_width : $bottom_width;
$new_height = $top_height + $bottom_height;

// create new image and merge
$new = imagecreate($new_width, $new_height);
imagecopy($new, $top, 0, 0, 0, 0, $top_width, $top_height);
imagecopy($new, $bottom, 0, $top_height+1, 0, 0, $bottom_width, $bottom_height);

// save to file
imagepng($new, 'merged_image.png');
netcoder
  • 66,435
  • 19
  • 125
  • 142
1
$photo_to_paste = "photo_to_paste.png";
$white_image = "white_image.png";

$im = imagecreatefrompng($white_image);
$im2 = imagecreatefrompng($photo_to_paste);


// Place "photo_to_paste.png" on "white_image.png"
imagecopy($im, $im2, 20, 10, 0, 0, imagesx($im2), imagesy($im2));

// Save output image.
imagepng($im, "output.png", 0);
Muhammad Azeem
  • 1,129
  • 1
  • 12
  • 16
  • May not be the answer to this question but this does not deserve a downvote for the reason this is the answer IF you want both images on top of each other – Wanjia Jan 06 '18 at 16:54
1

To achieve this you would have to a) Combine the image and store the result in a file b) generate a suitable tag to point to it. c) Avoid using that filename again, until that person had left.

If you want to combine two images just once, then use image magic.

If you frequently want to display two images one under the other, do so using suitable html, and let the browser do it.

E.g. Put the images in a

<div><div><img.../></div><div><img .../></div></div> 

which you generate with php in the normal way. (Which is easier than getting tags to appear here :)

Ian
  • 1,941
  • 2
  • 20
  • 35
  • 2
    This doesn't sound at all like what he asked for... without knowing his use-case, this probably isn't a viable solution. I'm guessing he wants to do it for CSS sprites. – mpen Nov 28 '10 at 01:11