Search code examples
phpimage-processingtransparencygd

PHP: Merging images into an alpha translucent image with GD


I'm trying to create an image with varying level of transparency, using GD. But I can get only fully transparent or fully opaque pixels in the image.

What I want to get:                                                      What I actually get:

(source: bx.at.ua)

                                                               
(source: bx.at.ua)


(source: bx.at.ua)

      
(source: bx.at.ua)

Here's a piece of the code I used to create images like this one ▲ fixed code:

$im=imagecreatetruecolor($sx,$sy);
imageantialias($im,true);
imagesavealpha($im,true);

$c00FF00=imagecolorallocate($im,0,255,0);
$cFFFFFF=imagecolorallocate($im,255,255,255); $cFFFFFF_00=imagecolorallocatealpha($im,255,255,255,127); imagecolortransparent($im,$cFFFFFF);

imagefilledrectangle($im,0,0,$sx,$sy,$cFFFFFF$cFFFFFF_00);

$sim=imagecreatefrompng('gradient.png');
imagecopy($im,$sim,$dest_x,$dest_y,0,0,imagesx($sim),imagesy($sim));
imagedestroy($sim);

imagettftext($im,$size,0,$text_x,$text_y,$c00FF00,$font,'Test');

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

What can I do to get the desired (translucent) result?


Solution

  • You need to call imagesavealpha() against your imported PNG ($sim) before merging, as well as against the final image.