繁体   English   中英

PHP GD文本不流畅

[英]PHP GD text is not smooth

问题截图:

在此输入图像描述

我试图获得相同的字体质量,如Font Squirrel的样本字体小部件 ,但字体不断出现粗糙。 它在Photoshop中很流畅。 注意:“懒狗”部分并没有被我加粗,它本身就是这样做的。

这是PHP:

<?php 
putenv('GDFONTPATH=' . realpath('.'));

$font = $_GET['font'] . '.ttf';
$text = 'The Quick Brown Fox Jumps over the Lazy Dog';

// Create the image
function imageCreateTransparent($x, $y) { 
    $imageOut = imagecreate($x, $y);
    $colourBlack = imagecolorallocate($imageOut, 0, 0, 0);
    imagecolortransparent($imageOut, $colourBlack);
    return $imageOut;
}

$image = imageCreateTransparent(600, 800);

// Create some colors
$white = imagecolorallocate($image, 255, 255, 255);
$grey = imagecolorallocate($image, 128, 128, 128);
$black = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 399, 29, $white);



// Add the text
imagettftext($image, 20, 0, 10, 20, $black, $font, $text);
imagepng($image);
imagealphablending($image, true);
imagedestroy($image);
?>

HTML: <img src="fontgen.php?font=Aller_Rg" alt="" />

如何获得字体的高质量结果?

您只将背景的一部分设置为白色,其余部分是透明的。

当在白色背景上绘制字体时,黑色文本会消除锯齿,使其看起来很平滑,这会导致字体周围的像素被绘制为两种颜色之间的混合,这也使字体看起来更小。

在右侧没有背景颜色,因此抗锯齿功能无法正常工作。 绘图算法不是在字体颜色和背景颜色之间进行混合,而是使用原始字体颜色来处理甚至部分被字母覆盖的任何像素。

这使得字母看起来“粗体”,因为边缘像素现在是黑色,而不是灰色阴影。

正确解决此问题的方法是使用具有适当背景颜色的图像,即使该背景颜色是透明的。 这使得图像库使用适当的alpha通道(这是进行alpha混合的唯一合理方式)而不是使用基于索引的alpha,其中只有一个'颜色'是透明的而所有其他颜色都是完全不透明的。

$font = '../../fonts/Aller_Rg.ttf';
$text = 'The Quick Brown Fox Jumps over the Lazy Dog';

// Create the image
function imageCreateTransparent($x, $y) {
    $imageOut = imagecreatetruecolor($x, $y);
    $backgroundColor = imagecolorallocatealpha($imageOut, 0, 0, 0, 127);
    imagefill($imageOut, 0, 0, $backgroundColor);
    return $imageOut;
}

$image = imageCreateTransparent(600, 800);

// Create some colors
$white = imagecolorallocate($image, 255, 255, 255);
$grey = imagecolorallocate($image, 128, 128, 128);
$black = imagecolorallocate($image, 0, 0, 0);

imagefilledrectangle($image, 0, 0, 399, 29, $white);

//// Add the text
imagettftext($image, 20, 0, 10, 20, $black, $font, $text);
//imagealphablending($image, true); //not needed as we created the image with alpha
imagesavealpha($image, true);
//imagepng($image, '../../var/log/wtf5.png');
imagepng($image);
imagedestroy($image);

这将使字体大小正确,因为抗锯齿将正常工作*并且图像将在适当的位置透明,例如使用上面的代码创建的图像,在红色背景上显示。 在此输入图像描述

具有白色背景的图像的位是白色的,图像的透明位使红色通过,并且文本对两者都正确地消除锯齿。

*假设您想要对背景颜色设置为反别名,但情况并非总是如此,但可能就在这里。

我怀疑是因为你只在左边400像素中使背景显式为白色。 在它的右边,它可能仍然是透明的,并有一些副作用。 r是首先出现在您之前创建的白色背景之外的字母。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM