-2

I have two images which are loaded from an external URL. I want to place one image on top of another (keeping the size). I actually don't know the sizes of the images as they are from an external URL and are different each time.

So I want a function which can be called like merge($url1,$url2,$final_name). I have googled on this but none worked.

I want this 3.png :

--------------------------------------------------------------------------
                                                                          |
                              IMAGE 1                                     |
                                                                          |
                                                                          |
___________________________________________________________________________

                                                                          |
                              IMAGE 2                                     |
                                                                          |
                                                                          |
___________________________________________________________________________

$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');

This does the job but the merged image loses its color and becomes nearly black and white like this:

enter image description here

PeeHaa
  • 71,436
  • 58
  • 190
  • 262

2 Answers2

1

Instead of this:

// create new image and merge
$new = imagecreate($new_width, $new_height);

I used:

// create new image and merge
$new = imagecreatetruecolor($new_width, $new_height);

It worked!

Thanks!

ArtKorchagin
  • 4,801
  • 13
  • 42
  • 58
0

i looked up ur code but i would save the folder in something like that:

$time = date('d-M-Y') . '-TIME-' . date('H-i-s');    
$save_finalimage_socialmedia = public_path("storage/image-{$time}.jpeg");
        imagejpeg($new, $save_finalimage_socialmedia);

PS: i did it in the jpeg format, so if you want, you can change in ur format (png,jpg,...) PS: @user4273356 ur code worked for me

Jakob Kichel
  • 3
  • 1
  • 3