php 实现将文本、图片写到同一张图上面以及文本的自动换行

以laravel框架为例:

首先controller中引用ImageManager;

use Intervention\Image\ImageManager;

下面就是关键处理,

  

$date = date('Y年m月d日 H:i', $data['time']);
$title = $data['title'];
$content = $data['content'];
$id = $data['id'];
//原图地址-画布
$dir = env('UPLOAD_FILE_ORIGINAL_DIR', 'Thumb') . '/' .env('UPLOAD_FILE_TEMP_DIR', 'Temp');
$baseImage = 'news_base.png';
$baseFile = public_path($dir.'/'.$baseImage);

//生成图片地址
$shareImage = $dir.'/' .$id. '.png';
$shareFile = public_path($shareImage);

//插入画布的图片
$img = public_path($img);

//图片处理方法类
$manager = new ImageManager();
$fontTtf = public_path('fonts/DroidSansFallback.ttf');

$image = $manager->make($baseFile)
//insert text
->text($date, 219, 384, function ($font) {
$font->file($fontTtf);
$font->size(30);
$font->color('#FCA969');
$font->align('left');
});
//这个部分尤为重要:当文本中出现数字时,根据字符串长度换行,行末会出现多余空格,所以决定用下面的这种根据宽度实现自动换行
function autowrap($fontsize, $angle, $fontface, $string, $width) {
// 参数分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
$content = "";
// 将字符串拆分成一个个单字 保存到数组 letter 中
preg_match_all("/./u", $string, $arr);
$letter = $arr[0];
foreach($letter as $l) {
$teststr = $content.$l;
$testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
if (($testbox[2] > $width) && ($content !== "")) {
$content .= PHP_EOL;
}
$content .= $l;
}
return $content;
}

$i=577; //top
$box = autowrap(30, 0, $fontTtf, $title, $i);

$image = $image->text($box, 113, $i, function ($font) {
$font->file(public_path('fonts/DroidSansFallback.ttf'));
$font->size(34);
$font->color('#222222');
$font->align('top');
});

//insert content
$i=715; //top
$box = autowrap(30, 0, $fontTtf, $content, $i);
$image = $image->text($box, 117, $i, function ($font) {
$font->file(public_path('fonts/DroidSansFallback.ttf'));
$font->size(30);
$font->color('#666666');
$font->align('top');
});

//insert img
$image = $image->insert($img, 'bottom-left', 115, 450);

$image->save($shareFile);

好了!到这里就实现了,如果你中间也遇到自动换行效果不是很好的时候,就好好看看标红的部分找找原因吧~~

猜你喜欢

转载自www.cnblogs.com/a-record/p/9233125.html