如何创建具有透明背景的图像

时间:2011-12-08 21:05:08

标签: php gdlib

如何使用具有透明背景的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);

此处背景为黑色

6 个答案:

答案 0 :(得分:26)

添加一行

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

imagestring之前的某个地方,它将是透明的。

0x7fff0000分解为:

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

完全透明。

答案 1 :(得分:9)

像这样......

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

答案 2 :(得分:8)

您必须使用imagefill()并使用已设置为0的已分配颜色(imagecolorallocatealpha())填充该内容。

正如@mvds所说,“分配是没有必要的”,如果它是真彩色图像(24或32位),它只是一个整数,所以你可以将该整数直接传递给imagefill()

当你调用imagecolorallocate()时,PHP在后台为truecolor图像做了什么是同样的事情 - 它只返回那个计算的整数。

答案 3 :(得分:6)

这应该有效:

$img = imagecreatetruecolor(900, 350);

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

答案 4 :(得分:6)

这应该有效。它对我有用。

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

答案 5 :(得分: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创建水印图像,建议您使用“Save for Web”命令并使用以下设置:

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