Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GD in PHP, how can I make a transparent PNG watermark on PNG and GIF files ? (JPG files work fine)

I have an image (let's call it original image) on which I want to watermark another image (let's call it logo).
The logo is a transparent PNG, whereas the original image can be png, jpg, or gif.
I have the following code:

function watermarkImage($originalFileContents, $originalWidth, $originalHeight) {
    $logoImage = imagecreatefrompng('logo.png');
    imagealphablending($logoImage, true);

    $logoWidth  = imagesx($logoImage);  
    $logoHeight = imagesy($logoImage);

    $originalImage = imagecreatefromstring($originalFileContents);

    $destX = $originalWidth  - $logoWidth;
    $destY = $originalHeight - $logoHeight;

    imagecopy(
        // source
        $originalImage,
        // destination
        $logoImage,
        // destination x and y
        $destX, $destY,
        // source x and y
        0, 0,
        // width and height of the area of the source to copy
        $logoWidth, $logoHeight
    );
    imagepng($originalImage);
}

This code works good (good = keep the transparency of the logo) only when the original image is a JPG file.
When the original file is a GIF or PNG, the logo has a solid white background, meaning the transparency is not working.

Why ? What do I need to change so it'll work ?
Thanks

UPDATE:
Here is my recoded version:

function generate_watermarked_image($originalFileContents, $originalWidth, $originalHeight, $paddingFromBottomRight = 0) {
    $watermarkFileLocation = 'watermark.png';
    $watermarkImage = imagecreatefrompng($watermarkFileLocation);
    $watermarkWidth = imagesx($watermarkImage);  
    $watermarkHeight = imagesy($watermarkImage);

    $originalImage = imagecreatefromstring($originalFileContents);

    $destX = $originalWidth - $watermarkWidth - $paddingFromBottomRight;  
    $destY = $originalHeight - $watermarkHeight - $paddingFromBottomRight;

    // creating a cut resource
    $cut = imagecreatetruecolor($watermarkWidth, $watermarkHeight);

    // copying that section of the background to the cut
    imagecopy($cut, $originalImage, 0, 0, $destX, $destY, $watermarkWidth, $watermarkHeight);

    // placing the watermark now
    imagecopy($cut, $watermarkImage, 0, 0, 0, 0, $watermarkWidth, $watermarkHeight);

    // merging both of the images
    imagecopymerge($originalImage, $cut, $destX, $destY, 0, 0, $watermarkWidth, $watermarkHeight, 100);
}
like image 747
Doron Avatar asked Dec 14 '10 09:12

Doron


1 Answers

imagecopy does not support using two images with alpha channels. take a look at imagecopymerge.

http://php.net/manual/en/function.imagecopymerge.php

There are plenty examples in the user comments sections, and a finished implementation for what you want:

http://www.php.net/manual/en/function.imagecopymerge.php#92787

like image 105
Oliver A. Avatar answered Oct 19 '22 17:10

Oliver A.