phpgdimagecreatefrompng

Merge two images with GD Library, have 1 repeat in background


I want to take an image that has transparency and then overlay that on top of a 60x60 (arbitrary size) image that repeats for the width and length of the first image...

So essentially use image 2 as a repeating background image that image 1 is on top of.

EDIT:

Okay, so I used One Trick Pony's solution, but tried to modify it to create a square image out of a rectangle if the width is less than the height, but not stretch the original image and instead center it. I was able to center the image but then the repeating background does not continue repeating after the overlay image stops.

Here is the code:

    <?php

    $overlay    = imagecreatefrompng('../images/' . $_REQUEST['overlay']);

    $repeating  = '../images/' . $_REQUEST['repeating'];
    $ext = explode('.', $_REQUEST['repeating']);
    $ext = strtolower($ext[1]);


    if ($ext == 'gif')
        $repeating  = imagecreatefromgif($repeating);
    elseif ($ext == 'png')
        $repeating  = imagecreatefrompng($repeating);
    elseif ($ext == 'jpg' || $ext == 'jpeg')
        $repeating  = imagecreatefromjpeg($repeating);


    $w          = imagesx($overlay);
    $h          = imagesy($overlay);
    if ($w < $h) 
        $w = $h;

    $output = imagecreatetruecolor($w, $h);
    imagealphablending($output, true);


    imagesettile($output, $repeating);
    imagefill($output, 0, 0, IMG_COLOR_TILED);
    imagedestroy($repeating);    

    $offsetx = ($w - imagesx($overlay)) / 2;

    imagecopy($output, $overlay, $offsetx, 0, 0, 0, $w, $h);
    imagedestroy($overlay);


    header('Content-Type: image/png');
    imagepng($output);
    imagedestroy($output);



    ?>

EDIT 2:

Overlay: http://72.167.52.68/~viisi/ebaylist/images/back_test2.png

Repeating: http://72.167.52.68/~viisi/ebaylist/images/back_test.gif

Expected result (but continue the repeating across the whole image): http://72.167.52.68/~viisi/ebaylist/image/previewImage.php?overlay=back_test2.png&repeating=back_test.gif


Solution

  • $overlay = imagecreatefrompng('/path/to/transparent/image.png');
    $repeating = imagecreatefrompng('/path/to/repeating/image.png');
    
    // create a new image matching overlay size
    $w = imagesx($overlay);
    $h = imagesy($overlay);
    $output = imagecreatetruecolor($w, $h);
    imagealphablending($output, true);
    imagesavealpha($output, true);
    
    // tile repeating image on it
    imagesettile($output, $repeating);
    imagefill($output, 0, 0, IMG_COLOR_TILED);
    imagedestroy($repeating);    
    
    // now add overlay on top
    imagecopy($output, $overlay, 0, 0, 0, 0, $w, $h);
    imagedestroy($overlay);
    
    // send to screen
    header('Content-Type: image/png');
    imagepng($output);
    imagedestroy($output);