我想使用PHP的GD功能创建一个透明的png图像。 具体来说,我的文字具有不同的不透明度级别(用于抗锯齿)。 使用以下代码,我可以在后台的主要部分创建一个alpha:
//Create image
$image = imagecreatetruecolor($width, $height);
//Set background to opaque
imagecolortransparent($image, imagecolorallocate($image, 0, 0, 0));
虽然它确实正确地创建了一个alpha,但在区域中图像的不透明度级别不是0%或100%,它会变黑。 如何在图像中正确创建这些区域的不透明度级别?
答案 0 :(得分:0)
具体来说,我的文字具有不同的不透明度(对于 抗混叠)
对文本使用不同的不透明度级别不会对其进行反锯齿。并且没有理由这样做,因为无论如何GD都会输出抗锯齿文本。
示例1:这会创建一个带有不透明黑色背景的图像,其中白色文字处于不同的不透明度级别
// create image resource.
$img = imagecreatetruecolor(250, 200);
// create image colours.
$black = imagecolorallocate($img, 0, 0, 0);
$white_0 = imagecolorallocatealpha($img, 255, 255, 255, 0);
$white_25 = imagecolorallocatealpha($img, 255, 255, 255, 32);
$white_50 = imagecolorallocatealpha($img, 255, 255, 255, 64);
$white_75 = imagecolorallocatealpha($img, 255, 255, 255, 96);
$white_100 = imagecolorallocatealpha($img, 255, 255, 255, 127);
// set background to opaque black.
imagefill($img, 0, 0, $black);
// output text strings.
imagettftext($img, 20, 0, 10, 30, $white_0, 'arial.ttf', '0% transparent');
imagettftext($img, 20, 0, 10, 60, $white_25, 'arial.ttf', '25% transparent');
imagettftext($img, 20, 0, 10, 90, $white_50, 'arial.ttf', '50% transparent');
imagettftext($img, 20, 0, 10, 120, $white_75, 'arial.ttf', '75% transparent');
imagettftext($img, 20, 0, 10, 150, $white_100, 'arial.ttf', '100% transparent'); // not visible!
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
结果1:
示例2:如果您想要的是透明背景:
// create image resource.
$img = imagecreatetruecolor(250, 200);
// save alpha channel information (for transparent background).
imagealphablending($img, false);
imagesavealpha($img, true);
// create image colours.
$transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
$black_0 = imagecolorallocatealpha($img, 0, 0, 0, 0);
$black_25 = imagecolorallocatealpha($img, 0, 0, 0, 32);
$black_50 = imagecolorallocatealpha($img, 0, 0, 0, 64);
$black_75 = imagecolorallocatealpha($img, 0, 0, 0, 96);
// set background to transparent.
imagefill($img, 0, 0, $transparent);
// output text strings.
imagettftext($img, 20, 0, 10, 30, $black_0, 'arial.ttf', '0% transparent');
imagettftext($img, 20, 0, 10, 60, $black_25, 'arial.ttf', '25% transparent');
imagettftext($img, 20, 0, 10, 90, $black_50, 'arial.ttf', '50% transparent');
imagettftext($img, 20, 0, 10, 120, $black_75, 'arial.ttf', '75% transparent');
imagettftext($img, 20, 0, 10, 150, $transparent, 'arial.ttf', '100% transparent'); // not visible!
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
结果2: