在图像中添加透明水印

时间:2014-02-18 17:14:32

标签: php

我需要添加透明水印(最终图像的透明度 - 80%)。我创建了这个函数来处理它:

function ImageAddWatermark($im, $stamp, $onLeft, $onTop, $margin){       
        // $stamp = imagecreatformpng(...) -> GD resource?
        // not important part - it calculates position of watermark 
        if($onLeft){
            $orgX = $margin;
        } else {
            $orgX = imagesx($im)-$margin-imagesx($stamp);
        }

        if($onTop){
            $orgY = $margin;
        }else {
            $orgY = imagesy($im)-$margin-imagesy($stamp);
        }

        imagecopymerge($im, $stamp, $orgX, $orgY, 0, 0, imagesx($stamp), imagesy($stamp), 50);

        return $im;
    }

功能结果: error

但是imagecopymerge返回黑色背景而不是透明。我甚至听到了一些意见,即imagecopymerge不是创建透明水印的正确方法......

所以问题是:“如何在jpeg照片中添加透明水印(使用alpha?)?”我怎样才能摆脱那个黑色的背景?(原来的PNG文件是透明的)

1 个答案:

答案 0 :(得分:1)

好吧,我找到了解决方案:

function ImageAddWatermark($im, $stamp, $onLeft, $onTop, $margin){

    if($onLeft){
        $orgX = $margin;
    } else {
        $orgX = imagesx($im)-$margin-imagesx($stamp);
    }

    if($onTop){
        $orgY = $margin;
    }else {
        $orgY = imagesy($im)-$margin-imagesy($stamp);
    }

    // creating a cut resource 
    $cut = imagecreatetruecolor(imagesx($stamp), imagesy($stamp)); 

    // copying relevant section from background to the cut resource 
    imagecopy($cut, $im, 0, 0, $orgX, $orgY, imagesx($stamp), imagesy($stamp)); 

    // copying relevant section from watermark to the cut resource 
    imagecopy($cut, $stamp, 0, 0, 0, 0, imagesx($stamp), imagesy($stamp)); 

    // insert cut resource to destination image 
    imagecopymerge($im, $cut, $orgX, $orgY, 0, 0, imagesx($stamp), imagesy($stamp), 50); 

    return $im;
}