[英]How can I align text to an image automatically in PHP?
我有几行代码来生成带有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);
我希望该图像根据给定的段落自动调整文本。 怎么做?
您可以尝试以下方法:(基于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;
}
给出这样的结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.