11

如何使用 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);

这里背景是黑色的

4

6 回答 6

30

添加一行

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

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

0x7fff0000分解为:

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

这是完全透明的。

于 2011-12-08T21:09:01.020 回答
13

像这样的东西...

$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);
于 2011-12-08T21:25:22.340 回答
9

您必须使用imagefill()分配的颜色 ( ) 并将其填充为imagecolorallocatealpha()alpha 设置为 0。

正如@mvds 所说,“不需要分配”,如果它是真彩色图像(24 位或 32 位),它只是一个整数,因此您可以将该整数直接传递给imagefill().

当您调用时,PHP 在后台对真彩色图像所做的imagecolorallocate()事情是相同的——它只是返回计算得到的整数。

于 2011-12-08T21:20:30.047 回答
8

这应该有效:

$img = imagecreatetruecolor(900, 350);

$color = imagecolorallocatealpha($img, 0, 0, 0, 127); //fill transparent back
imagefill($img, 0, 0, $color);
imagesavealpha($img, true);
于 2015-01-19T15:22:19.833 回答
7

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

$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);
于 2017-10-04T12:13:55.120 回答
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 图像;因此不推荐。

如果您使用 Adob​​e 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%
于 2013-06-08T11:13:45.880 回答