Search code examples
phpgdimagick

How do I create a transparant area inside a non transparant solid color image using GD or Imagick?


Using imagick and GD Library I tried to make a square image with a transparent center. I tried to do it like this :

$img = imagecreatetruecolor($width, $height); 

imagefilledrectangle($img, $left, $top, $right, $bottom, imagecolorallocate($img, 255, 255, 255)); 
imagecolortransparent($img, imagecolorallocate($img, 255, 255, 255));   

ob_start();    
ini_set('memory_limit', '-1');              
imagepng($img, './imagecolortransparent.png');
$blob = ob_get_clean();     

However the end result is always not transparent for the center small box. Am I doing this wrong somewhere? Any help will be appreciated :(.

enter image description here


Solution

  • You must activate imagesavealpha to get transparency.

    imagesavealpha($img,true);
    imagepng($img, './imagecolortransparent.png');