21

The situation is this: I have a small 50x50 pic. I also have a small 50x50 transparent picture which contains a frame for the 50x50 pic, so I basically want to put the transparent png on top of the image and merge those two which would lead to a final third picture that looks something like this: http://img245.imageshack.us/i/50x50n.png

Note: I don't want to do this using HTML only (I achieved this by writing a javascript plugin that put the transparent png on top of the original image).

Thanks.

subZero
  • 5,056
  • 6
  • 31
  • 51

3 Answers3

30

You can merge the two images together using the PHP GD2 library.

Example:

<?php
 # If you don't know the type of image you are using as your originals.
 $image = imagecreatefromstring(file_get_contents($your_original_image));
 $frame = imagecreatefromstring(file_get_contents($your_frame_image));

 # If you know your originals are of type PNG.
 $image = imagecreatefrompng($your_original_image);
 $frame = imagecreatefrompng($your_frame_image);

 imagecopymerge($image, $frame, 0, 0, 0, 0, 50, 50, 100);

 # Save the image to a file
 imagepng($image, '/path/to/save/image.png');

 # Output straight to the browser.
 imagepng($image);
?>
Mykola
  • 3,343
  • 6
  • 23
  • 39
zanbaldwin
  • 999
  • 8
  • 28
  • I tried this but my transparent frame just went white on the middle. what's suppose to be the problem. – Aivan Monceller Feb 08 '12 at 09:06
  • you might want to add `header('Content-Type: image/png');` before the last line to ensure the correct MIME type is sent to the browser – Dirk Hartzer Waldeck May 16 '12 at 06:04
  • This didn't work for me either, it doesn't seem to save the alpha channel. I also tried adding the alpha blending flag mentioned by the user below. – Gazillion Jun 27 '12 at 20:18
8

Add imagealphablending($frame,true); before imagecopymerge() if you want to keep PNG frame transparancy over the image.

Community
  • 1
  • 1
Raf
  • 81
  • 1
  • 1
4

You can do it using ImageMagick :: Composite. The first user contributed note should be enough to grasp the concept.

Alex Gyoshev
  • 11,929
  • 4
  • 44
  • 74