笔记 · · 8 阅读

laravel生成二维码

生成二维码带文字

<?php

namespace App\Listeners\Product;

use App\Events\Product\AssetCreatedEvent;
use App\Libraries\Log\MLog;
use App\Models\AssetModel;
use SimpleSoftwareIO\QrCode\Generator;

/**
 * 生成资产二维码
 * 2023-7-3 14:57:36 lmy
 * Class GenerateAssetQRCodeListener
 * @package App\Listeners\Product
 */
class GenerateAssetQRCodeListener
{

    public function handle($event)
    {
        if ($event instanceof AssetCreatedEvent) {
            try {
                $itemid = $event->id;
                $info = AssetModel::find($itemid);

                // 生成资产二维码 2023-5-16 16:11:09 lmy
                if (!empty($info->qrcode)) {
                    return;
                }
//                dd($info->qrcode);
                $uriTime = $info->uri . time();
                $qrcode = 'asset/' . $uriTime . '.png';
                $filename = base_path() . '/public/' . $uriTime . '.png';
                $generate = (new Generator())
                    ->format('png')
                    ->size(200)->margin(2)->generate(json_encode([
                        'uri' => $info->uri,
                        'type' => 'asset'
                    ]), $filename);

                //创建图片的实例
                $file_ = base_path() . '/public/' . $info->uri . time() . '.png';
                $dst = imagecreatefrompng($filename); // imagecreatefromstring(file_get_contents($dst_path));
                $src = imagecreate(200, 230);
                $background_color = imagecolorallocate($src, 255, 255, 255);
                //将覆盖图复制到目标图片上,最后个参数100是设置透明度(100是不透明),这里实现不透明效果
                imagecopymerge($src, $dst, 0, 0, 0, 0, 200, 200, 100);    //位置可以自己调试
                $color = imagecolorallocate($src, 0, 0, 0); // 文字颜色
                imagettftext($src, 16, 0, 12, 215, $color, base_path('public/simhei.ttf'), $info->uri); // 创建文字
                imagepng($src, $file_);

                app('Oss')->putObject($qrcode, file_get_contents($file_));
//                $img[] = 'https://uhd-cdn.oss-cn-hangzhou.aliyuncs.com/testtestqrcode.png';
                unlink($filename); // 删除文件
//                unlink($file_); // 删除文件
                $info->qrcode = $qrcode;
                $info->save();
            } catch (\Exception $exception) {
                MLog::error("asset", $exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
            }
        }
    }

}