How to create an image with transparent background How to create an image with transparent background php php

How to create an image with transparent background


Add a line

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

somewhere before the imagestring and it will be transparent.

0x7fff0000 breaks down into:

alpha = 0x7fred = 0xffgreen = 0x00blue = 0x00

which is fully transparent.


Something like this...

$im = @imagecreatetruecolor(100, 25);# important part oneimagesavealpha($im, true);imagealphablending($im, false);# important part two$white = imagecolorallocatealpha($im, 255, 255, 255, 127);imagefill($im, 0, 0, $white);# do whatever you want with transparent image$lime = imagecolorallocate($im, 204, 255, 51);imagettftext($im, $font, 0, 0, $font - 3, $lime, "captcha.ttf", $string);header("Content-type: image/png");imagepng($im);imagedestroy($im);


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.