参考AlecRust的想法,我实现了PNG文本服务。
示例在这里:
http://lingtalfi.com/services/pngtext?color=cc0000&size=10&text=Hello%20World
有四个参数:
- text:要显示的字符串
- font:未使用,因为我的演示只有Arial.ttf。
- fontSize:整数(默认为12)
- color:六位十六进制码
请勿直接使用此服务(除了测试),而是使用我创建的提供该服务的类:
https://github.com/lingtalfi/WebBox/blob/master/Image/PngTextUtil.php
class PngTextUtil
{
public static function displayPngText(string $text, array $options = []): void
{
if (false === extension_loaded("gd")) {
throw new WebBoxException("The gd extension is not loaded!");
}
header("Content-type: image/png");
$font = $options['font'] ?? "arial/Arial.ttf";
$fontsize = $options['fontSize'] ?? 12;
$hexColor = $options['color'] ?? "000000";
if ('/' !== substr($font, 0, 1)) {
$fontDir = __DIR__ . "/../assets/fonts";
$font = $fontDir . "/" . $font;
}
$rgbColors = ConvertTool::convertHexColorToRgb($hexColor);
$charWidth = $fontsize;
$charFactor = 1;
$textLen = mb_strlen($text);
$imageWidth = $textLen * $charWidth * $charFactor;
$imageHeight = $fontsize;
$logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
imagealphablending($logoimg, false);
imagesavealpha($logoimg, true);
$col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
imagefill($logoimg, 0, 0, $col);
$white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]);
$x = 0;
$y = $fontsize;
$angle = 0;
$bbox = imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text);
$boxWidth = $bbox[4] - $bbox[0];
$boxHeight = $bbox[7] - $bbox[1];
imagedestroy($logoimg);
$imageWidth = abs($boxWidth);
$imageHeight = abs($boxHeight);
$logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
imagealphablending($logoimg, false);
imagesavealpha($logoimg, true);
$col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
imagefill($logoimg, 0, 0, $col);
$white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]);
$x = 0;
$y = $fontsize;
$angle = 0;
imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text);
imagepng($logoimg);
imagedestroy($logoimg);
}
}
注意:如果您不使用
Universe框架,则需要替换此行:
$rgbColors = ConvertTool::convertHexColorToRgb($hexColor)
使用以下代码:
$rgbColors = sscanf($hexColor, "%02x%02x%02x");
如果您的十六进制颜色必须正好为六个字符长度(不要在其前面加上井号(#))。
注意:最终,我没有使用这个服务,因为我发现字体很丑,更糟糕的是:无法选择文本。但是为了讨论的目的,我认为这段代码值得分享...
${\textsf{\color{lightgreen} 你好,世界!}}$
- undefined