1
0
modern-qrcode/app/Services/QRCodeService.php
2025-04-14 16:35:05 +08:00

78 lines
2.1 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Services;
use Intervention\Image\Facades\Image;
use Exception;
class QRCodeService
{
protected $phpqrcode;
protected $tempDir;
public function __construct()
{
$this->tempDir = storage_path('app/temp');
if (!file_exists($this->tempDir)) {
mkdir($this->tempDir, 0777, true);
}
// 引入PHP QR Code库
require_once base_path('vendor/phpqrcode/qrlib.php');
$this->phpqrcode = new \QRcode();
}
public function generate(string $text, int $size, string $errorCorrection = 'M', ?string $logoPath = null)
{
$tempFile = $this->tempDir . '/' . md5($text . time()) . '.png';
// 设置错误纠正级别
$errorCorrectionLevel = match($errorCorrection) {
'L' => QR_ECLEVEL_L,
'M' => QR_ECLEVEL_M,
'Q' => QR_ECLEVEL_Q,
'H' => QR_ECLEVEL_H,
default => QR_ECLEVEL_M
};
try {
// 生成二维码
$this->phpqrcode->png($text, $tempFile, $errorCorrectionLevel, $size);
// 如果提供了Logo则合并Logo
if ($logoPath) {
$this->mergeLogo($tempFile, $logoPath);
}
// 读取生成的图片
$qrCode = file_get_contents($tempFile);
// 删除临时文件
unlink($tempFile);
return $qrCode;
} catch (Exception $e) {
if (file_exists($tempFile)) {
unlink($tempFile);
}
throw $e;
}
}
protected function mergeLogo(string $qrCodePath, string $logoPath)
{
$qrCode = Image::make($qrCodePath);
$logo = Image::make($logoPath);
// 调整Logo大小不超过二维码的1/4
$logoSize = min($qrCode->width(), $qrCode->height()) / 4;
$logo->resize($logoSize, $logoSize, function ($constraint) {
$constraint->aspectRatio();
});
// 在二维码中心添加Logo
$qrCode->insert($logo, 'center');
$qrCode->save($qrCodePath);
}
}