How to change transparency of image (in GD2) ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
voidman
Forum Newbie
Posts: 9
Joined: Wed Nov 12, 2008 3:25 am

How to change transparency of image (in GD2) ?

Post by voidman »

Hello, all!

I have a task to convert any image (Jpg, Gif..) into Png with specified transparency.
All I will set is Opacity Value (Ex: 40%)

I've found a way to set transparency level for true color images with "imagecopymerge" by setting opacity value in the last argument but It didn't help me.

Here is my "unlucky" code:

Code: Select all

 
   $opacityVal = 50;
 
   $src_img =  imagecreatefrompng('example.png');
   $scr_w = imagesx($src_img);      
   $scr_h = imagesy($src_img);      
 
   imagesavealpha($src_img, true); 
   imagealphablending($src_img, true); 
   
   $final_img   = imagecreatetruecolor($scr_w, $scr_h);
          
   imagesavealpha($final_img, true); 
   imagealphablending($final_img, false); 
   
   $color = imagecolortransparent($final_img);    
   
   imagefilledrectangle($final_img, 0, 0,$scr_w, $scr_h, $color);  
   
   imagecopymerge($final_img, $src_img, 0, 0, 0, 0,$scr_w, $scr_h, $opacityVal); 
   
   $src_img = $final_img;    
   
   
   header("Content-Type: image/png"); 
   imagepng($src_img); 
 
As result I have my image with some transparency "overlayed" on the white background, but not transparent at all.

Thank you forward for help!
Post Reply