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); } }