Laravel 后台为微信小程序生成海报图片(嵌入带参数的小程序码)

更新日期: 2018-10-09 阅读次数: 9552 分类: Laravel

思路

  • 首先我需要一张海报 (随便找张大图做测试用)

Laravel 安装 intervention/image

composer require intervention/image

报错

Using version ^2.4 for intervention/image
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - symfony/event-dispatcher v4.0.0 requires php ^7.1.3 -> your PHP version (7.0.18) does not satisfy that requirement.
    - symfony/event-dispatcher v4.0.0 requires php ^7.1.3 -> your PHP version (7.0.18) does not satisfy that requirement.
    - Installation request for symfony/event-dispatcher (locked at v4.0.0) -> satisfiable by symfony/event-dispatcher[v4.0.0].

Installation failed, reverting ./composer.json to its original content.

修改 composer.json

-        "php": ">=7.0.0",
+        "php": "^7.0",

删除 composer.lock 文件,重新执行 composer install

rm composer.lock
composer install

修改 config/app.php

$providers 部分添加

Intervention\Image\ImageServiceProvider::class

$aliases 部分添加

'Image' => Intervention\Image\Facades\Image::class

如何实现 - 开始看文档之旅

创建背景图

http://image.intervention.io/api/make

make — Create a new image resource

Image::make 接口,异常的 NB,可以使用

  • 本地路径,例如 public/image/白夜追凶.jpg
  • URL,直接使用七牛 CDN 的图片。需要注意的是:URL of an image (allow_url_fopen must be enabled).

填充图片 - 将二维码/小程序码填充到当前背景图中

http://image.intervention.io/api/fill

fill — fill image with color or pattern

保存图片

save — Save image in filesystem

fill 是否支持图片二进制流

支持

string - Binary image data.

实现

实际调试时,发现 fill 的效果根本不行,位置也不对,甚至看不见。。。

后来搜索了一下,发现应该使用 insert。(疑问,fill 在什么场合使用呢? canvas?)

use Image;
use Storage;

// 向背景图中填充小程序码
$img = Image::make(Storage::disk('public')->get('background.png'));
$img->insert($qrcode_img, 'bottom-right', 10, 10);
$storage_path  = Storage::disk('public')->getDriver()->getAdapter()->getPathPrefix();
$img->save($storage_path."/".$target_image_name);

$rsp['data'] = Storage::disk("public")->url($target_image_name);
return response()->json($rsp);

生成的图片无法访问 404

解决方法:

php artisan storage:link

这行命令执行的操作是创建了一个软链接 public/storage,指向 storage/app/public。

再次访问图片就可以了。

参考

  • https://github.com/Intervention/image

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式