【问题标题】:How can I align text to an image automatically in PHP?如何在 PHP 中自动将文本与图像对齐?
【发布时间】:2014-10-08 12:50:40
【问题描述】:

我有几行代码可以在 php 中生成带有一些给定文本的纯图像。但是当我为图像文本指定宽度时,它会超出图像。如何将图像内的文本与固定宽度但动态高度对齐?我的代码如下。

header ("Content-type: image/png");
$string = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s';                                            
$font   = 4;
$width  = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);

$im = @imagecreate (200,500);
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, 0, 0,  $string, $text_color);
imagepng ($im);

我希望这张图片能够根据给定的段落自动调整文本。该怎么做?

【问题讨论】:

  • 我在另一个项目中遇到了很多麻烦,因为字母间距和每个字母的宽度你无法以可接受的方式做到这一点。除了使用 php 创建图像,您可以做的是,使用文本创建一个简单的 html 文件,然后使用 phantomjs 截取屏幕截图并在该文件夹中创建图像。相信我,这将是最简单的方法。 phantomjs 非常简单,可以在几秒钟内完成您所要求的任何事情。这是您需要的:phantomjs.org/screen-capture.html

标签: php image image-generation


【解决方案1】:

你可以试试这个: (基于 gannon 在http://php.net/manual/en/function.imagestring.php 的贡献)

header ("Content-type: image/png");
$string = "Lorem Ipsum is simply dummy\n text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s";
$im = make_wrapped_txt($string, 0, 4, 4, 200);
imagepng ($im);

function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) {
  if (strlen($color) != 6) $color = 000000;
  $int = hexdec($color);
  $h = imagefontheight($font);
  $fw = imagefontwidth($font);
  $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
  $lines = count($txt);
  $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
  $bg = imagecolorallocate($im, 255, 255, 255);
  $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
  $y = 0;
  foreach ($txt as $text) {
    $x = (($w - ($fw * strlen($text))) / 2); 
    imagestring($im, $font, $x, $y, $text, $color);
    $y += ($h + $space);
  }
  return $im;
}

给出这样的结果:

【讨论】:

  • 太棒了。谢谢。现在我可以根据我的要求对其进行修改。需要一个想法。 :)
  • 还有一个疑问。如何使用一些自定义字体。如果我将该字体文件保存在根文件夹中,我该如何在此处包含?
  • 只需使用 $my_font = imageloadfont('./your_font.gdf');然后 imagestring($im, $my_font...
  • 谢谢。我尝试过使用 ttf 文件。但不工作。只有 gdf ​​可以吗?有什么想法吗?
猜你喜欢
  • 2021-10-20
  • 2012-09-29
  • 2021-01-24
  • 2011-01-14
  • 1970-01-01
  • 2019-05-30
  • 1970-01-01
相关资源
最近更新 更多