PHP GD文本不平滑

PHP GD文本不平滑,php,fonts,gd,Php,Fonts,Gd,问题截图: 我试图得到相同的字体质量,如,但字体总是出来粗糙。在Photoshop中它是平滑的。注:“懒狗”部分不是我给的,它是自己做的 以下是PHP: <?php putenv('GDFONTPATH=' . realpath('.')); $font = $_GET['font'] . '.ttf'; $text = 'The Quick Brown Fox Jumps over the Lazy Dog'; // Create the image function image

问题截图:

我试图得到相同的字体质量,如,但字体总是出来粗糙。在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:


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

我怀疑这是因为您只在左侧400像素处显式地将背景置为白色。在右边,它可能仍然是透明的,并且有一些副作用。
r
是您先前创建的白色背景之外的第一个字母。

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

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

右侧没有背景色,因此消除混叠无法正常工作。绘图算法不是在字体颜色和背景颜色之间混合,而是对任何像素使用原始字体颜色,甚至部分被字母覆盖

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

正确解决这一问题的方法是使用具有适当背景颜色的图像,即使该背景颜色是透明的。这使得图像库使用适当的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);
这将使字体大小正确,因为消除混叠将正常工作*并且图像将在适当情况下透明,例如,使用上述代码创建的图像,显示在红色背景上

具有白色背景的图像位是白色的,透明的图像位让红色通过,文本对这两种颜色都进行了正确的抗锯齿处理


*假设您希望将背景颜色设置为什么样的反别名,情况并非总是如此,但可能在这里。

那么我需要更改什么来解决此问题?我认为imageCreateTransparent(600800);是全宽。
imagefilledrectangle($image,0,0,399,29,$white)未覆盖整个宽度。完美。谢谢你,我真的很感谢你花时间向我解释为什么会发生这种情况。我从中学到了!非常感谢。