PHP GD渲染Unicode专用区域(PUA)字体

4
我正在尝试在商业网站开发项目中使用 font-awesome 字体堆栈,我们已将其置于工作阶段,但仍面临一个问题。
当在移动设备上查看我们的网站时(或浏览器不支持导入字体堆栈),所有图标都被替换为方块(因为 font-awesome 使用 Unicode 字符来表示图标)。
这破坏了我们网站的外观和感觉(特别是我们编写的自定义管理面板)。
我们想出的解决方法是退回到使用 PHP 渲染包含所需图标的图像(颜色等指定为参数之一的大小等)。
以前从未有过此问题,但现在我很难让 PHP 渲染出专用区域 (PUA) 字符。
以下是我正在尝试使用的一些示例代码:
<?php
  $icons = array(
    "icon-glass" => "\f000",
    "icon-music" => "\f001",
    "icon-search" => "\f002",
    // [...]
  );
  $font = "_assets/fonts/font-awesome/fontawesome-webfont.ttf";
  if(isset($_GET['icon'])) {
    $chr = $icons[$_GET['icon']];
    header("Content-type: image/png");
    $img = imagecreatetruecolor($_GET['w'], $_GET['h']);
    imagealphablending($img, true);
    $transparent = imagecolorallocatealpha( $img, 0, 0, 0, 127 );
    imagefill( $img, 0, 0, $transparent );
    $black = imagecolorallocate($img, 255, 0, 0);
    imagettftext($img, 20, 0, 32, 32, $black, $font, $chr);
    imagesavealpha($img, true);
    imagepng($img);
    exit;
  }
?>
<div style="background-color:black; width:64px; height:64px;">
  <img src="dev?icon=icon-dashboard&w=64&h=64">
</div>
<br />
<div style="background-color:blue; width:64px; height:64px;">
  <img src="dev?icon=icon-bolt&w=64&h=64">
</div>

然而,这似乎只是渲染图像内部的方块。我认为这是因为我没有正确地将Unicode字符输入到PHP中,可能是我忽略了一些非常愚蠢的东西。
欢迎任何建议。

参考此链接,这是Font-Awesome堆栈的URL:http://fortawesome.github.com/Font-Awesome/#overview - R4wizard
绘制正方形意味着您使用的字体中没有可用的字符。字体路径是否正确?或者,您可以预先生成所需图标的图像(不是按需生成,而是作为一次性操作),并将它们保存在服务器上。 - dda
字体路径正确,我认为我的问题要么在于 Unicode 字符的格式,要么是 gd 无法处理字体的 PUA。 - R4wizard
1个回答

4
我使用的PHP代码来呈现Font Awesome TTF字形(大部分):
$text = json_decode('"&#xF099;"');
...
imagesavealpha($im, true);
$trans = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $trans);
imagealphablending($im, true);

$fontcolor = imagecolorallocatealpha($im, 0, 0, 0, 0);

// Add the text
imagettftext($im, $x, 0, 0, 0, $fontcolor, $font, $text);
imagesavealpha($im, true);
imagepng($im);
imagedestroy($im);

json-decode()函数处理unicode字符的复杂性。我使用了GD 2或更高版本,因此必须使用点而不是像素。
我的完整类考虑了所需的高度,但忽略了宽度。您可以在https://github.com/sperelson/awesome2png查看它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接