如何使用具有透明背景的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);
Run Code Online (Sandbox Code Playgroud)
这里的背景是黑色的
mvd*_*vds 27
添加一行
imagefill($image,0,0,0x7fff0000);
Run Code Online (Sandbox Code Playgroud)
在imagestring它之前的某个地方,它将是透明的.
0x7fff0000 分解为:
alpha = 0x7f
red = 0xff
green = 0x00
blue = 0x00
Run Code Online (Sandbox Code Playgroud)
这是完全透明的.
像这样......
$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);
Run Code Online (Sandbox Code Playgroud)
您必须使用imagefill()并使用imagecolorallocatealpha()已设置为0的已分配颜色()填充该颜色.
正如@mvds所说,"分配是没有必要的",如果它是真彩色图像(24或32位),它只是一个整数,所以你可以直接传递该整数imagefill().
当你调用时,PHP在后台为truecolor图像做的imagecolorallocate()是同样的事情 - 它只返回计算的整数.
小智 6
这应该工作:
$img = imagecreatetruecolor(900, 350);
$color = imagecolorallocatealpha($img, 0, 0, 0, 127); //fill transparent back
imagefill($img, 0, 0, $color);
imagesavealpha($img, true);
Run Code Online (Sandbox Code Playgroud)
小智 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);
Run Code Online (Sandbox Code Playgroud)