【问题标题】:Make image just fit to a text使图像适合文本
【发布时间】:2011-10-24 14:09:33
【问题描述】:

我正在使用 PHP GD 并尝试绘制文本并调整图像大小 刚好适合文字。

我发现了这个问题并尝试了 Martin Geisler 的代码。

Resize image size according to size of text

它看起来工作正常,但是当我尝试其他文本时,有些文本脱离了图像。

当然,我可以添加额外的填充,但所需的填充取决于文本。 这太临时了。

有人知道正确的方法吗?

提前致谢。

// Martin Geisler's version using MS Gothic
header("Content-type: image/png");

$q     = 'Image example';
$font  = './msgothic.ttc';  // MS Gothic
$size  = 30;
$bbox   = imageftbbox($size, 0, $font, $q);

$width  = $bbox[2] - $bbox[6];
$height = $bbox[3] - $bbox[7];

$im    = imagecreatetruecolor($width, $height);
$green = imagecolorallocate($im, 60, 240, 60);

imagefttext($im, $size, 0, -$bbox[6], -$bbox[7], $green, $font, $q);
imagepng($im);
imagedestroy($im);

http://www.betatechnology.jp/~ao/imageexample.png

【问题讨论】:

标签: php gd


【解决方案1】:

这是与您正在编写的文本的宽度有关的问题。 除非您使用固定字体,否则 3 i 小于 3 o。

与其尝试创建具有完全正确比例的图像,我宁愿将其制作得足够大,然后裁剪掉其周围未使用的空间。

创建图像后,您可以将边框设为纯色,然后对其进行裁剪。 有关如何进行裁剪的说明,请参见此处:

Crop whitespace from image in PHP

【讨论】:

  • 谢谢你,发现。我会试试看。但似乎没有办法从 PHP 获得精确的边界框。我查看了 PHP GD 代码,发现它调用了 freetype 的 FT_Glyph_Get_CBox 函数。 freetype 文档说这个函数不是为了得到精确的 bbox。 freetype.org/freetype2/docs/reference/…
猜你喜欢
  • 1970-01-01
  • 2014-06-02
  • 1970-01-01
  • 2013-05-25
  • 2021-04-08
  • 1970-01-01
  • 2013-03-24
  • 2016-08-09
  • 2011-06-20
相关资源
最近更新 更多