GD 库的抗锯齿功能设计比较简单,仅支持开启和关闭,底层的实现是由 GD 库自身控制的,没有暴露出细粒度的调节接口。因此你不能直接通过 imageantialias() 调整抗锯齿的程度。
使用更高分辨率绘制再缩小
这是常用的“超采样抗锯齿”(Supersampling Anti-Aliasing)思路。你先以更大的尺寸绘制图像,开启抗锯齿,再通过 imagecopyresampled() 缩小到目标大小,能明显改善锯齿问题。
<?php
$width = 200;
$height = 200;
// 创建两倍尺寸画布
$largeWidth = $width * 2;
$largeHeight = $height * 2;
$largeImage = imagecreatetruecolor($largeWidth, $largeHeight);
imageantialias($largeImage, true);
$white = imagecolorallocate($largeImage, 255, 255, 255);
$black = imagecolorallocate($largeImage, 0, 0, 0);
imagefilledrectangle($largeImage, 0, 0, $largeWidth, $largeHeight, $white);
// 绘制线条或图形,坐标放大两倍
imageline($largeImage, 10 * 2, 10 * 2, 190 * 2, 190 * 2, $black);
// 创建目标画布
$finalImage = imagecreatetruecolor($width, $height);
imagecopyresampled($finalImage, $largeImage, 0, 0, 0, 0, $width, $height, $largeWidth, $largeHeight);
header('Content-Type: image/png');
imagepng($finalImage);
imagedestroy($largeImage);
imagedestroy($finalImage);
?>
使用 Imagick 替代 GD
如果你对抗锯齿有更高要求,推荐使用 ImageMagick 的 PHP 扩展 Imagick。它支持更多抗锯齿控制,比如设置滤镜和采样方式,效果更好且参数更丰富。
示例:
<?php
$imagick = new Imagick();
$imagick->newImage(200, 200, new ImagickPixel('white'));
$draw = new ImagickDraw();
$draw->setStrokeColor('black');
$draw->setStrokeWidth(2);
$draw->setFillColor('none');
$draw->setStrokeAntialias(true);
$draw->line(10, 10, 190, 190);
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick;
?>
手动实现抗锯齿算法
这需要较强的图像处理知识,一般不推荐,除非对抗锯齿效果有特殊需求。
$image = imagecreatefrompng('https://m66.net/path/to/image.png');