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
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.
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.
Something like this...
$im = @imagecreatetruecolor(100, 25);
# important part one
imagesavealpha($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);
This should work:
$img = imagecreatetruecolor(900, 350);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127); //fill transparent back
imagefill($img, 0, 0, $color);
imagesavealpha($img, true);
This should work. It has worked for me.
$thumb = imagecreatetruecolor($newwidth,$newheight);
$transparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
imagefill($thumb, 0, 0, $transparent);
imagesavealpha($thumb, true);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($thumb, $output_dir);
Sometime you will not get transparent image due to problems in PNG image. The image should be in one of the following recommended formats:
PNG-8 (recommended)
Colors: 256 or less
Transparency: On/Off
GIF
Colors: 256 or less
Transparency: On/Off
JPEG
Colors: True color
Transparency: n/a
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:
File Format: PNG-8, non-interlaced
Color Reduction: Selective, 256 colors
Dithering: Diffusion, 88%
Transparency: On, Matte: None
Transparency Dither: Diffusion Transparency Dither, 100%
来源:https://stackoverflow.com/questions/8437665/how-to-create-an-image-with-transparent-background