一个快速函数,用于从字符串自动生成多行图像,图像大小会根据字符串本身自动计算。
<?php
function multilineimage($string){
$string = str_replace("\r","",$string);
$string = explode("\n",$string);
$maxlen = 0;
foreach ($string as $str){
if (strlen($str) > $maxlen){
$maxlen = strlen($str);
}
}
$font_size = 4;
$width = imagefontwidth($font_size)*$maxlen;
$height = imagefontheight($font_size) * count($string);
$img = imagecreate($width,$height);
$bg = imagecolorallocate($img, 205, 255, 255);
$color = imagecolorallocate($img, 0, 0, 0);
$ypos = 0;
foreach ($string as $str){
$len = strlen($str);
for($i=0;$i<$len;$i++){
$xpos = $i * imagefontwidth($font_size);
imagechar($img, $font_size, $xpos, $ypos, $str, $color);
$str = substr($str, 1);
}
$ypos = $ypos + imagefontheight($font_size);
}
header("Content-Type: image/gif");
imagegif($img);
imagedestroy($img);
}
multilineimage("This is an image
This is line 2\nLine 3
Line 4");
?>