粗略写了使用GD2制作文字图像demo

项目要求宽,高为传入参数;文字大小,文字间隔需要自动调节;

由于imagettftext()函数写入文字坐标点不以画布左上角为原点,而是根据文字的字体类型,字体大小,中英文,标点等因素变换(测试多组数据,Y轴0坐标点位于一个字体宽度左右位置),所以文字居中问题还未得到解决;

由于文字坐标

<?php
class Index
{
private $config = array(
'width' => '160',
'height' => '90',
'frame' => '0.05',

// 默认背景色红色,字体白色
'imageColor' => array(220,20,60,0),
'fontColor' => array(255,255,255,0),

'extend' => array(
'fontType' => 'c:/windows/fonts/simhei.ttf', // 字体类型
),
);

public function newimage($text = '测试',$options = array())
{
header("Content-type: text/html; charset=utf-8");

$options = $_GET;

$text = $_GET['text'];


$this->config = array_merge($this->config,$options);

$location = array(0,0,0);

$imageColor = $this->config['imageColor'];
$fontColor = $this->config['fontColor'];

$width = $this->config['width'];
$height = $this->config['height'];

//处理中英,标点计算字符长度
$strlength = $this->utf8_strlen($text);

// 计算边框长度
$padding = $this->config['frame'];

if( $padding < 0.5 )
{
// 百分比 以短边为标准计算padding
$padding = $height*$padding*2;
}
else
{
$padding = $padding*2;
}

// 去掉边框的有效长度
$width_1 = $width-$padding;
$height_1 = $height-$padding;

// 判断单个字体长度和高的大小
if( $strlength >=1 )
{
$oneBox = $width_1/$strlength;
}
else
{
exit('字符不能为空');
}

if( $oneBox > $height_1 )
{
$oneBox = $height_1;

if( $strlength <=1 )
{
// 一个字符
$gap = 0;

$location[1] = ($width - $oneBox)/2;
}
else
{
// 计算横向间距
$gap = ($width_1 - ($oneBox*$strlength))/($strlength-1);

$location[1] = $padding/2;
}

$location[2] = ($padding/2)+$oneBox;
// $location[2] = ($height-($padding/2)+$oneBox)*0.5;
}
else
{
$gap = 0;

$location[1] = $padding/2;

// 计算纵向坐标Y
$location[2] = (($height-$oneBox)/2)+$oneBox;
// $location[2] = ($height-($padding/2)+$oneBox)*0.5;
}

// 字体磅数计算
$size = 72*$oneBox/96;

// 分割中文字体为数组
$fontArr = preg_split('/(?<!^)(?!$)/u', $text );

// 调试
if($_GET['debug'] === 'true')
{
print_r('字符长度:'.$strlength . '<br/>');
print_r('字符磅数:'.$size . '<br/>');

print_r('单个字符:' . $oneBox . '<br/>');
print_r('边距:' . $padding/2 . '<br/>');
print_r('去掉边框的高度:' . $height_1 . '<br/>');

var_dump($fontArr);
exit();
}

$font = $this->config['extend']['fontType'];

//创建空白图片的长 、高
$img = imagecreate($width, $height);

//给图片分配颜色
imagecolorallocatealpha($img, $imageColor[0], $imageColor[1], $imageColor[2] ,$imageColor[3]);

//设置字体颜色
$color = imagecolorallocatealpha($img, $fontColor[0], $fontColor[1], $fontColor[2] ,$fontColor[3]);

//将ttf文字写到图片中
foreach ($fontArr as $key => $value)
{
imagettftext($img, $size, $location[0], $location[1]+($oneBox+$gap)*($key), $location[2], $color, $font, $value);

// imagestring($img, 5, $location[1]+($oneBox+$gap)*($key), $location[2], $value,$color);
}

//发送头信息
header('Content-Type: image/png');

imagepng($img);

imagedestroy($img);

}

// 计算中文字符串长度
public function utf8_strlen($string = null)
{
// 将字符串分解为单元
preg_match_all("/./us", $string, $match);
// 返回单元个数
return count($match[0]);
}
}

$obj = new Index();

$obj->newimage();

原文地址:https://www.cnblogs.com/yokooo/p/7867268.html