Bohdi
Bohdi

Reputation: 1305

Merging two images in PHP

I'm building a web application where you can design something, at the end of the process it outputs two images. One is a gif and the other is a jpeg. I am looking to take both images and merge them into one image. However after trying a few techniques none seem to work.

My script is as follows:

$imgl = $_GET['img1'];
$img2 = $_GET['img2'];


$dest = imagecreatefromjpeg('$imgl');
$src = imagecreatefromgif('$img2');

// Copy and merge
imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);

However the image that is displayed is just shows a non image icon. The variables $img1 and $img2 contain an image path, to a folder where the images exsist. I know this because when I echo the two variables in a html img tag, both images are displayed. Can anyone tell me where my script is going wrong?

Upvotes: 1

Views: 2755

Answers (3)

The Wavelength
The Wavelength

Reputation: 2914

You should remove the single quotation marks. They stop PHP from looking up for variables in the string. For more information on quotation mark usage in PHP, take a look here.

Means:

$dest = imagecreatefromjpeg($imgl);
$src = imagecreatefromgif($img2);

Additionally, you should do checks whether you want to allow the manipulation of an image. You allow EVERYONE who knows the names of the GET-parameters to put a possible malicious file path into it. You do not prevent this.

Useful functions are realpath, basename and file_exists.

Upvotes: 1

Baba
Baba

Reputation: 95161

I know your example is directly for PHP DOC but i also tested it and it does not work for me .. with a little work around it should work

$imgl = "a.jpg";
$img2 = "f.gif";

$dest = imagecreatefromjpeg($imgl);
$src = imagecreatefromgif($img2);
imagecolortransparent($src, imagecolorat($src, 0, 0));

$src_x = imagesx($src);
$src_y = imagesy($src);
imagecopymerge($dest, $src, 0, 0, 0, 0, $src_x, $src_y, 100);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);

Upvotes: 1

user428517
user428517

Reputation: 4193

Not 100% sure this will fix your problem, but it's certainly a syntax error. This:

$dest = imagecreatefromjpeg('$imgl');
$src = imagecreatefromgif('$img2');

Should be:

$dest = imagecreatefromjpeg($imgl);
$src = imagecreatefromgif($img2);

You want to pass the values of $img1 and $img2, not the literal strings '$img1' and '$img2'.

Upvotes: 0

Related Questions