0

How can I embed a dynamic image created with GD inside another dynamic image generated with GD? Both files work fine if they are separated, but when I try to use one inside the another it doesn't work.

Image 1:

<?php
header('Content-type: image/png');
$image1 = imagecreatefrompng('images/image1.png');

//add some texts to image 1

imagepng($image1);

imagedestroy($image1);
?>

Image 2:

<?php
header('Content-type: image/png');
$image2 = imagecreatefrompng('images/image2.png');

//add some texts to image 2

imagepng($image2);

imagedestroy($image2);
?>

Now, if I try to use image generated in image2.php inside image1.php:

<?php
header('Content-type: image/png');
$image1 = imagecreatefrompng('images/image1.png');
$image2 = imagecreatefromgd('image2.php');

//add some texts to image1
imagecopy($image1, $image2, $x, $y, $src_x, $src_y, $src_w, $src_h);

imagepng($image1);

imagedestroy($image1);
imagedestroy($image2);
?>

Any ideas? Thanks!

Aнгел
  • 1,361
  • 3
  • 17
  • 32
  • I don't think imagecreatefromgd takes a file .php extension as input. Refer http://php.net/manual/en/function.imagecreatefromgd.php – Ajay Jun 28 '16 at 05:43
  • well, I tested with "imagecreatefrompng" but neither was able to generate the image I was expecting :( – Aнгел Jun 28 '16 at 14:02
  • I tried your code with some values of $x,$y.$src_x,$src_y,$src_w,$src_h and it worked, checkout http://php.net/manual/en/function.imagecopy.php for further refernce. – Ajay Jun 28 '16 at 15:07
  • it works if both image1 and image2 are actual PNGs [$image1 = imagecreatefrompng('images/image1.png'); $image2 = imagecreatefromgd('image2.png');] but if $image2 is an image generated in another php file then it doesn't works... for instance: image2 is an image generated using barcode php file from here http://davidscotttufts.com/2009/03/31/how-to-create-barcodes-in-php/ – Aнгел Jun 28 '16 at 17:54

1 Answers1

1

Great!! After testing different solutions, here's the way it worked. Basically, all images generated with GD must be created in the same file to send one only image to the browser:

<?php

header('Content-type: image/png');
$image1 = imagecreatefrompng('images/image1.png');
$image2 = createImage2();

//add some texts to image1
imagecopy($image1, $image2, $x, $y, $src_x, $src_y, $src_w, $src_h);

imagepng($image1);

imagedestroy($image1);
imagedestroy($image2);



function createimage2() {
    $image2 = imagecreatefrompng('images/image2.png');

    //add some texts to image 2
    return $image2
?>
Aнгел
  • 1,361
  • 3
  • 17
  • 32