ivop
ivop

Reputation: 85

Combine two PNG transparent images

I'm trying to create a function to resize transparent PNG images and adding a transparent PNG watermark to them. I have tried to place imagealphablending($image_p, false); and imagesavealpha($image_p,true); everywhere, but it it makes black background or crop the first image. Here is my code:

$newName=$this->filename;
list($OrigWidth, $OrigHeight)=$this->info;
if($OrigHeight>$OrigWidth){
    $pomer=$OrigWidth/$OrigHeight;
    $NewHeight=$h;
    $NewWidth=$NewHeight*$pomer;
}else{
    $pomer=$OrigHeight/$OrigWidth;
    $NewWidth=$w;
    $NewHeight=$NewWidth*$pomer;
}

$image_p=imagecreatetruecolor($NewWidth, $NewHeight);
if($this->ext=="jpg")
$image=imagecreatefromjpeg($newName);
elseif($this->ext=="png")
$image=imagecreatefrompng($newName);
elseif($this->ext=="gif")
$image=imagecreatefromgif($newName);

if($this->ext=="png" or $this->ext=="gif"){ //průhlednost
    imagealphablending($image_p, false);
    imagesavealpha($image_p,true);
    $transparent = imagecolorallocatealpha($image_p, 255, 255, 255, 127);
    imagefilledrectangle($image_p, 0, 0, $NewWidth, $NewHeight, $transparent);
}

if(($OrigWidth>$w or $OrigHeight>$h) and $w!=0)
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $NewWidth, $NewHeight, $OrigWidth, $OrigHeight);
else
    $image_p=$image; //není třeba zmenšovat

if($vodoznak!=""){ //if watermark is set
    //imagealphablending($image_p, false);
    //imagesavealpha($image_p,true);
    $watermark = imagecreatefrompng($vodoznak);     
    $ww = imagesx($watermark);
    $wh = imagesy($watermark);
    if($umisteni{0}=="0") $x=3; else $x=$OrigWidth-$ww-3;       
    if($umisteni{1}=="0") $y=3; else $y=$OrigHeight-$wh-3;
    imagealphablending($watermark, false);
    imagesavealpha($watermark,true);
    imagecopy($image_p, $watermark, $x, $y, 0, 0, $ww, $wh);
}

if($this->ext=="jpg")
imagejpeg($image_p, $copypath, $komprese);
elseif($this->ext=="png")
imagepng($image_p, $copypath);
elseif($this->ext=="gif")
imagegif($image_p, $copypath);

I don't know, where I shall place alpha settings, please help. Thank you for every advice!

Upvotes: 6

Views: 846

Answers (1)

froddd
froddd

Reputation: 362

The imagesavealpha function needs to be applied to the image you're pasting onto the one you created, so to $image instead of $image_p:

imagealphablending($image, true);
imagesavealpha($image,true);

Just like you did with the watermark!

Upvotes: 3

Related Questions