开发者

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);
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜