From e58664cff6d52fbbc9aa73b1f1c07db97f3b0e03 Mon Sep 17 00:00:00 2001 From: chengxl Date: Thu, 8 May 2025 14:09:28 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=9F=E6=88=90=E4=BA=8C=E7=BB=B4=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/common/QrCodeImage.php | 99 ++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 application/common/QrCodeImage.php diff --git a/application/common/QrCodeImage.php b/application/common/QrCodeImage.php new file mode 100644 index 0000000..b855e2b --- /dev/null +++ b/application/common/QrCodeImage.php @@ -0,0 +1,99 @@ +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()); + } + } +} +?> \ No newline at end of file