如何在 PHP 生成的图像中使用天气图标 Web 字体


How can I use a weather icons web font in an image generated by PHP?

我想在动态生成的PHP图像中使用这些图标,以便人们可以将天气嵌入他们的网页上。

现在我正在使用met.no的天气服务,它提供了一个称为"symbol"的整洁属性,是一个整数。 1 = 晴天,2 = 多云等。天气图标存储库上的拉取请求包括 met.no 映射,这很酷,因为我可以调用echo "<i class='wi wi-yrno-$symbol'></i>";并始终获得正确的图标。

但是我不知道如何使用PHP的图像创建函数来做到这一点。在Javascript中,你可以这样做:以编程方式按名称获取FontAwesome unicode值,但是在PHP中我将如何做到这一点?我想我只需要制作一系列array("wi-yrno-1 => "(unicode escape code here)", "wi-yrno-2" => "(another escape code here) ...但我想知道是否有更好的方法。

我假设您在服务器上生成图像,然后将该内容发送到浏览器。

你给出的 JavaScript 示例无关紧要。主要是因为字体已经加载并映射到类名。在 PHP 中,您必须重新创建此映射。将符号简单映射到十进制值即可。例如

$symbols = [0 => '&#xf00d;', 1 => ..., 2 => ..., ...];

设置映射后,您需要正在使用的字体文件的绝对路径。知道您将使用imagettftext在具有给定 ttf 字体文件的图像上绘制文本之后。它必须是 ttf 字体文件(因此函数的名称)。

// the symbol response from the met.no request
$symbolIntFromApi = 0;
// the mapping for the decimal characters
$symbols = [0 => '&#xf00d;'];
// create the image
$image = imagecreatetruecolor(1000, 1000);
// set background color to white
imagefill($image, 0, 0, imagecolorallocate($image, 255, 255, 255));
// write the text using the given font
imagettftext($image, 12, 0, 20, 20, 0, realpath('./font/weathericons-regular-webfont.ttf'), $symbols[$symbol]);
// save the image
imagepng($image, 'test.png');