如何在PHP中自动将文本与图像对齐?

如何在PHP中自动将文本与图像对齐?,php,image,image-generation,Php,Image,Image Generation,我有几行代码用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

我有几行代码用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非常简单,可以在几秒钟内完成任何要求。这就是你需要的:太棒了。谢谢现在我可以根据我的要求修改它了。需要一个想法。:)还有一个疑问。如何使用自定义字体。如果我把这个字体文件保存在根文件夹中,我怎么能包含在这里呢?只需使用$my_font=imageloadfont('./your_font.gdf');然后是imagestring($im,$my_font…)谢谢。我试过使用一个ttf文件。但不起作用。只有gdf会起作用?知道吗?
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;
}