Service.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace addons\qrcode\library;
  3. use Endroid\QrCode\ErrorCorrectionLevel;
  4. class Service
  5. {
  6. /**
  7. * 生成二维码
  8. * @param $params
  9. * @return \Endroid\QrCode\QrCode
  10. * @throws \Endroid\QrCode\Exception\InvalidPathException
  11. */
  12. public static function qrcode($params)
  13. {
  14. $config = get_addon_config('qrcode');
  15. $params = is_array($params) ? $params : [$params];
  16. $params = array_merge($config, $params);
  17. $params['labelfontpath'] = ROOT_PATH . 'public' . $config['labelfontpath'];
  18. $params['logopath'] = ROOT_PATH . 'public' . $config['logopath'];
  19. // 前景色
  20. list($r, $g, $b) = sscanf($params['foreground'], "#%02x%02x%02x");
  21. $foregroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];
  22. // 背景色
  23. list($r, $g, $b) = sscanf($params['background'], "#%02x%02x%02x");
  24. $backgroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];
  25. // 创建实例
  26. $qrCode = new \Endroid\QrCode\QrCode($params['text']);
  27. $qrCode->setSize($params['size']);
  28. // 高级选项
  29. $qrCode->setWriterByName($params['format']);
  30. $qrCode->setMargin($params['padding']);
  31. $qrCode->setEncoding('UTF-8');
  32. $qrCode->setErrorCorrectionLevel(new ErrorCorrectionLevel($params['errorlevel']));
  33. $qrCode->setForegroundColor($foregroundcolor);
  34. $qrCode->setBackgroundColor($backgroundcolor);
  35. // 设置标签
  36. if (isset($params['label']) && $params['label']) {
  37. $qrCode->setLabel($params['label'], $params['labelfontsize'], $params['labelfontpath'], $params['labelalignment']);
  38. }
  39. // 设置Logo
  40. if (isset($params['logo']) && $params['logo']) {
  41. $qrCode->setLogoPath($params['logopath']);
  42. $qrCode->setLogoSize($params['logosize'], $params['logosize']);
  43. }
  44. $qrCode->setRoundBlockSize(true);
  45. $qrCode->setValidateResult(false);
  46. $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);
  47. return $qrCode;
  48. }
  49. }