ManpreetSandhu
ManpreetSandhu

Reputation: 2155

How to merge two images and save in php?

I am creating an application in php in which i upload a image and resize it and place it on a Coffee Mug. Coffee mug is a background image of a div. Now i want to save both images as a single image it would look like a screenshot of a coffee mug with the image printed on it. How to take screenshot of only mug and image on it or if there is an another way to doing it in php.

Upvotes: 0

Views: 7504

Answers (2)

jlasarte
jlasarte

Reputation: 643

You can do this by using the GD2 library:

<?php

  $image = imagecreatefromstring(file_get_contents($image_path);
  $coffe_mug= imagecreatefromstring(file_get_contents($coffe_mug_path));

  // merge the two
  imagecopymerge($image, $coffe_mug, 10, 10, 0, 0, 100, 47, 75);

  // save, can also be imagepng, imagegif, etc, etc
  imagejpeg($image, '/path/to/save/image.png');

  ?>

You can also output the image to the browser, for more info check: http://php.net/manual/es/function.imagecopymerge.php.

Upvotes: 2

berkes
berkes

Reputation: 27553

You need an image library for that. Most PHP versions on many servers are precompiled with GD. This is a limited and not so well performing library, so most people will use Imagemagick.

In GD:

$mug = imagecreatefrompng('mug.jpg');
$overlay = imagecreatefromjpeg('photo.png');

imagecopy($mug, $overlay);

In Imagemagick:

$mug = new Imagick("mug.jpg");
$overlay = new Imagick("logo.png");
$composition = new Imagick();

$composition->compositeImage($mug);
$composition->compositeImage($overlay);

Upvotes: 2

Related Questions