How to create an image with transparent background

clarkk picture clarkk · Dec 8, 2011 · Viewed 37.2k times · Source

How to create an image with GDlib with a transparent background?

header('content-type: image/png');

$image = imagecreatetruecolor(900, 350);

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

$text_color = imagecolorallocate($image, 0, 51, 102);
imagestring($image,2,4,4,'Test',$text_color);

imagepng($image);
imagedestroy($image);

Here the background is black

Answer

mvds picture mvds · Dec 8, 2011

Add a line

imagefill($image,0,0,0x7fff0000);

somewhere before the imagestring and it will be transparent.

0x7fff0000 breaks down into:

alpha = 0x7f
red = 0xff
green = 0x00
blue = 0x00

which is fully transparent.