本代码配合生成海报插件使用,可以生成动态活动海报,比如个人推广二维码、商品推广等场景。
源码依赖 intervention/image ,使用前请先安装此拓展
composer require intervention/image
在 app/config/app.php 中添加
// 将下面代码添加到 providers 数组中
'providers' => [
// ...
Intervention\Image\ImageServiceProvider::class,
// ...
],
// 将下面代码添加到 aliases 数组中
'aliases' => [
// ...
'Image' => Intervention\Image\Facades\Image::class,
// ...
],
配合海报插件使用源码
public function laravel() { //接收前端的参数 $params = request()->all(); //将背景图写入本地 $bgImg = "bg-img.png"; file_put_contents("bg-img.png", file_get_contents($params['bg-img'])); $img = Image::make($bgImg); //处理图片 if (isset($params['image'])) { foreach ($params['image'] as $key => $image) { //将图片写入本地 $src = 'image-' . $key . '.png'; file_put_contents($src, file_get_contents($image['url'])); $img->insert($src, 'top-left', $image['x'], $image['y']); } } //处理文字 if (isset($params['text'])) { foreach ($params['text'] as $text) { $img->text($text['input'], $text['x'], $text['y'] + 24, function ($font) use ($text) { //此乃字体所在,请更换项目相应位置 $path = public_path('simhei.ttf'); $font->file($path); $font->size($text['size']); $font->color($text['color']); }); } } //生成海报,具体位置自定 $imgPath = time() . '.png'; $img->save($imgPath); }