2011-12-08 110 views
8

图像如何创建GDlib的图像与透明背景?如何创建带有透明背景

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); 

这里的背景是黑色

+0

你必须使用'imagefill'并填写与分配的颜色(imagecolorallocatealpha)有一个Alpha设置为0。 –

+0

@noice,创建答案..它的工作原理 – clarkk

+0

@NoICE:分配的颜色是没有必要的,它是一个真实的彩色图像。 – mvds

回答

7

你必须使用imagefill()并填写与分配的颜色(imagecolorallocatealpha())作为@mvds说,已经设置透明度为0。

,“分配是没有必要的”,如果是真彩色图像(24或32位),它仅仅是一个整数,这样你就可以直接进入imagefill()该整数。

PHP的确会在后台运行的真彩色图像当你调用imagecolorallocate()是同样的事情 - 它只是返回计算的整数。

21

imagestring之前添加一行

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

的地方,这将是透明的。

0x7fff0000分解成:

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

这是完全透明的。

+0

你让我的一天:)谢谢! –

8

事情是这样的......

$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); 
+0

这使我的透明背景的白色而不是黑色:(因为他们不为未来的读者多的信息请提供一些解释,你所写的内容 – Bolas

1

有时你不会得到透明图像由于PNG图像的问题。图像应采用以下推荐格式之一:

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 

imagecopymerge函数无法正确处理PNG-24图像;因此不推荐。

如果您在使用Adobe Photoshop创建水印图像,建议您使用以下设置“另存为网页”命令:

File Format: PNG-8, non-interlaced 
Color Reduction: Selective, 256 colors 
Dithering: Diffusion, 88% 
Transparency: On, Matte: None 
Transparency Dither: Diffusion Transparency Dither, 100% 
6

这应该工作:

$img = imagecreatetruecolor(900, 350); 

$color = imagecolorallocatealpha($img, 0, 0, 0, 127); //fill transparent back 
imagefill($img, 0, 0, $color); 
imagesavealpha($img, true); 
4

这应该工作。它为我工作。

$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); 
+0

唯一代码的答案的arent鼓励'救了我的一天。文件说, :'将该标志设置为试图保存完整的alpha通道信息(相对于单一颜色透明度)保存PNG images'时 – WhatsThePoint

+0

功能'imagesavealpha() –