2

I need to add transparent watermark (transparency in final image - 80%). I created this function to handle it:

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

Result of function: error

But imagecopymerge returns black background instead of transparent. I even heard some opinions, that imagecopymerge isn't exactly the right thing for creating transparent watermarks...

So the question is: "How can I add a transparent watermark (using alpha?) in jpeg photo?" How can I get rid of that black backgound? (In original PNG file is transparent)

tomascapek
  • 841
  • 1
  • 8
  • 20

1 Answers1

2

Well, I found the solution:

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;
}
tomascapek
  • 841
  • 1
  • 8
  • 20