【问题标题】:PHP GD Rendering Unicode Private Use Area (PUA) fontsPHP GD 渲染 Unicode Private Use Area (PUA) 字体
【发布时间】:2012-10-03 06:02:30
【问题描述】:

我正在尝试在一个商业 Web 开发项目中使用 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:fortawesome.github.com/Font-Awesome/#overview
  • 绘制正方形意味着字符在您使用的字体中不可用。字体路径是否正确?或者,您可以预先生成所需图标的图像(不是按需,而是作为一次性操作)并将它们保存在您的服务器上。
  • 字体路径是正确的,我想我的问题要么是 unicode 字符的格式,要么是 gd 无法处理字体的 PUA。

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


【解决方案1】:

我用来渲染 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查看。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2011-10-03
    • 2017-10-05
    • 2019-07-27
    • 1970-01-01
    相关资源
    最近更新 更多