phpgdlib

Add GD image inside another GD image


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!


Solution

  • 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
    ?>