Write the Code. Change the World.

9月 27

场景

有一个海报,里边有美丽的画面,还有一些需要填充的地府。比如,往海报中添加一个二维码,或加一段文字。

但是,这些二维码和文字是动态的。方便推广宣传,合成图片就很有必要了。

就拿关注微信公众号这件是吧。微信公众号,可以生成带场景值的二维码。推广的时候,合成成一张海报就方便使用了。

图片处理用 imagick 库

imagick 功能比较强大,方便各种图片的操作。

php 使用 image intervention

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

使用 composer 安装

composer require intervention/image

实现细节

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Image;

class ImageBuilderController extends Controller
{
    public function poster(Request $request)
    {
        $bg = 'static/image/group/groupbg.png';
        $description = '给你一个美丽的意外';
        $fonts = 'static/image/group/pingfang.ttf';

        $scene = $request->scene ? $request->scene : urlencode('xxxx');
        $avatar = $request->avatar ? $request->avatar : 'static/image/group/avatar.png';
        $nickname = $request->nickname ? $request->nickname : '神奇动物在哪里';
        $page = $request->page;

        $qrcode = $this->qrcode($scene, $page);
        $qrcodeImg = Image::make($qrcode)->resize(300, 300);
        $avatarImg = Image::make($avatar)->resize(100, 100);

        $image = Image::make($bg)->insert($qrcodeImg, 'bottom-left', 225, 196)
                                ->insert($avatarImg, 'bottom-left', 171, 511, function ($constraint) {
                                     $constraint->aspectRatio();
                                });

        $image->text($nickname, 288, 645, function($font) use ($fonts) {
            $font->file($fonts);
            $font->size(34);
            $font->color('#222');
        });

        $image->text($description, 288, 685, function($font) use ($fonts){
            $font->file($fonts);
            $font->size(24);
            $font->color('#888');
        });

        $folder = '/upload/image/wxapp/' . date('Ym', time()) . '/';
        $upload_path = public_path() . $folder;
        // 创建文件夹
        if (!file_exists($upload_path))
        {
            mkdir($upload_path, 0777, true);
        }
        $name = time() . '_' . str_random(10) . '.jpg';
        $image->save($upload_path . $name, 80);
        $image->destroy();

        return $this->response->array(['url' => url($folder . $name)])->setStatusCode(201);
    }

    private function qrcode($scene, $page)
    {
        $access_token = getAccessToken(env('WECHAT_MINI_PROGRAM_APPID'), env('WECHAT_MINI_PROGRAM_SECRET'));

        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";

        $params = ['scene' => $scene];
        if($page)
            $params['page'] = $page;

        $data = curl($url, json_encode($params), TRUE, TRUE);

        $check = json_decode($data);

        if($check && $check->errcode)
            return $this->response->errorUnauthorized($check->errmsg);

        return $data;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注