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

时间:2012-10-12 12:10:30

标签: php unicode fonts php-gd font-awesome

我试图在商业网站开发项目中使用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中,而且我可能会感到非常愚蠢。

欢迎任何建议。

1 个答案:

答案 0 :(得分:4)

我用来渲染Font Awesome TTF字形的PHP代码(主要是):

$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查看。