99 lines
3.1 KiB
PHP
99 lines
3.1 KiB
PHP
<?php
|
||
|
||
namespace app\common;
|
||
use Endroid\QrCode\Color\Color;
|
||
use Endroid\QrCode\ErrorCorrectionLevel;
|
||
use Endroid\QrCode\Logo\Logo;
|
||
use Endroid\QrCode\QrCode;
|
||
use Endroid\QrCode\Writer\PngWriter;
|
||
|
||
|
||
class QrCodeImage
|
||
{
|
||
/**
|
||
* 生成二维码
|
||
* @param string $content 内容
|
||
* @param string $savePath 保存路径(可选)
|
||
* @param int $size 尺寸(像素)
|
||
* @return mixed
|
||
*/
|
||
|
||
public static function generate($content, $size = 300, $savePath = '')
|
||
{
|
||
try {
|
||
// 创建二维码实例
|
||
$qrCode = new QrCode($content);
|
||
$qrCode->setSize($size);
|
||
$qrCode->setMargin(10);
|
||
|
||
// 设置颜色(RGB格式)
|
||
$qrCode->setForegroundColor(new Color(0, 0, 0));
|
||
$qrCode->setBackgroundColor(new Color(255, 255, 255)); // 白色
|
||
|
||
// 使用PNG写入器
|
||
$writer = new PngWriter();
|
||
$result = $writer->write($qrCode);
|
||
|
||
if ($savePath) {
|
||
// 确保目录存在
|
||
if (!is_dir(dirname($savePath))) {
|
||
mkdir(dirname($savePath), 0755, true);
|
||
}
|
||
$result->saveToFile($savePath);
|
||
return $savePath;
|
||
}
|
||
|
||
// 直接输出到浏览器
|
||
header('Content-Type: ' . $result->getMimeType());
|
||
echo $result->getString();
|
||
exit;
|
||
|
||
} catch (\Exception $e) {
|
||
// 记录错误日志
|
||
\think\Log::error('二维码生成失败: ' . $e->getMessage());
|
||
return false;
|
||
}
|
||
}
|
||
/**
|
||
* 生成带Logo的二维码
|
||
* @param string $content 内容
|
||
* @param string $logoPath Logo路径
|
||
* @param int $qrSize 二维码尺寸(像素)
|
||
* @param int $logoSize Logo尺寸(像素)
|
||
* @param string $savePath 保存路径(可选)
|
||
*/
|
||
public static function withLogo(string $content,string $logoPath,int $qrSize = 20,int $logoSize = 20,string $savePath = null) {
|
||
try {
|
||
// 基础二维码配置
|
||
$qrCode = new QrCode($content);
|
||
$qrCode->setSize($qrSize);
|
||
$qrCode->setMargin(20);
|
||
// $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH);
|
||
$qrCode->setForegroundColor(new Color(0, 0, 0));
|
||
$qrCode->setBackgroundColor(new Color(255, 255, 255));
|
||
|
||
// Logo配置
|
||
$logo = Logo::create($logoPath)
|
||
->setResizeToWidth($logoSize)
|
||
->setPunchoutBackground(true); // 透明背景穿透
|
||
|
||
// 合并生成
|
||
$writer = new PngWriter();
|
||
$result = $writer->write($qrCode, $logo);
|
||
|
||
// 输出或保存
|
||
if ($savePath) {
|
||
$result->saveToFile($savePath);
|
||
return $savePath;
|
||
}
|
||
|
||
header('Content-Type: ' . $result->getMimeType());
|
||
echo $result->getString();
|
||
exit;
|
||
|
||
} catch (\Exception $e) {
|
||
throw new \RuntimeException("生成失败: " . $e->getMessage());
|
||
}
|
||
}
|
||
}
|
||
?>
|