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
Add a line
somewhere before the
imagestring
and it will be transparent.0x7fff0000
breaks down into:which is fully transparent.
This should work. It has worked for me.
This should work:
Sometime you will not get transparent image due to problems in PNG image. The image should be in one of the following recommended formats:
The imagecopymerge function does not properly handle the PNG-24 images; it is therefore not recommend.
If you are using Adobe Photoshop to create watermark images, it is recommended that you use "Save for Web" command with the following settings:
You have to use
imagefill()
and fill that with allocated color (imagecolorallocatealpha()
) that have alpha set to 0.As @mvds said, "allocating isn't necessary", if it is a truecolor image (24 or 32bit) it is just an integer, so you can pass that integer directly to
imagefill()
.What PHP does in the background for truecolor images when you call
imagecolorallocate()
is the same thing - it just returns that computed integer.Something like this...