如何在需要时在动态图像中创建多个换行符?
目前,我的以下工作正常,没有任何问题(还)。
header ("Content-type: image/png");
$string = $_REQUEST['text'];
$font = 15;
$width = 300;
$height = 350;
$image = imagecreate($width, $height);
$back = ImageColorAllocate($image, 255, 255, 255);
$border = ImageColorAllocate($image, 0, 0, 0);
ImageFilledRectangle($image, 0, 0, $width, $height, $border);
ImageFilledRectangle($image, 1, 1, $width-2, $height-2, $back);
$text_color = imagecolorallocate($image, 255, 0, 0);
ImageStringWrap($image, $font, 3, 2, $string, $text_color, $width-2 );
imagepng($image);
function ImageStringWrap($image, $font, $x, $y, $text, $color, $maxwidth) {
$fontwidth = ImageFontWidth($font);
$fontheight = ImageFontHeight($font);
if ($maxwidth != NULL) {
$maxcharsperline = floor($maxwidth / $fontwidth);
$text = wordwrap($text, $maxcharsperline, "\n", false);
}
while (list($numl, $line) = each($lines)) {
ImageString($image, $font, $x, $y, $line, $color);
$y += $fontheight;
}
}
虽然上面的方法效果很好,但我一直未能解决的一件事是能够获得类似于 nl2br()
的换行符。
从 $_REQUEST['text']
中提取的文本来自数据库,该文本最初是从文本区域插入并通过 URL 传递到此脚本。当然,当人们在文本区域中输入内容时,会出现换行符。虽然通过文本将其打印到浏览器很容易,但我似乎无法在图像中获得相同的结果。
我没有花很长时间使用 GD 库,但是在搜索之后我真的找不到任何关于如何做到这一点的信息。难道这就是不可能吗?
Currently I've got the following working just fine without any problems (yet).
header ("Content-type: image/png");
$string = $_REQUEST['text'];
$font = 15;
$width = 300;
$height = 350;
$image = imagecreate($width, $height);
$back = ImageColorAllocate($image, 255, 255, 255);
$border = ImageColorAllocate($image, 0, 0, 0);
ImageFilledRectangle($image, 0, 0, $width, $height, $border);
ImageFilledRectangle($image, 1, 1, $width-2, $height-2, $back);
$text_color = imagecolorallocate($image, 255, 0, 0);
ImageStringWrap($image, $font, 3, 2, $string, $text_color, $width-2 );
imagepng($image);
function ImageStringWrap($image, $font, $x, $y, $text, $color, $maxwidth) {
$fontwidth = ImageFontWidth($font);
$fontheight = ImageFontHeight($font);
if ($maxwidth != NULL) {
$maxcharsperline = floor($maxwidth / $fontwidth);
$text = wordwrap($text, $maxcharsperline, "\n", false);
}
while (list($numl, $line) = each($lines)) {
ImageString($image, $font, $x, $y, $line, $color);
$y += $fontheight;
}
}
While the above works great, one thing I've been failing to work is be able to get line breaks like would come out akin to nl2br()
.
The text that this is pulling from in $_REQUEST['text']
is from the database, which was originally inserted from a textarea and passed to this script via URL. Naturally when people type in a textarea, there are line breaks that come from that. While printing it to the browser via text is easy, I can't seem to get the same result within an image.
I haven't spend a long time working with the GD library, but after searching around I really can't find anything about how to do this. Is it just not possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论