Qrcode.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace app\common;
  3. use Endroid\QrCode\Color\Color;
  4. use Endroid\QrCode\Encoding\Encoding;
  5. use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
  6. use Endroid\QrCode\Label\Label;
  7. use Endroid\QrCode\Logo\Logo;
  8. use Endroid\QrCode\QrCode as QrCodeQrCode;
  9. use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
  10. use Endroid\QrCode\Writer\PngWriter;
  11. class Qrcode{
  12. private $logo = null;
  13. private $label = null;
  14. private $size = 400;
  15. public function __construct()
  16. {
  17. //
  18. }
  19. /**
  20. * 设置二维码LOGO
  21. */
  22. public function setLogo($logo_path)
  23. {
  24. $this->logo = Logo::create($logo_path) //logo的照片路径
  25. ->setResizeToWidth(20); //logo的大小
  26. }
  27. /**
  28. * 设置二维码下方文字
  29. */
  30. public function setLabel($text)
  31. {
  32. $this->label = Label::create($text) //二维码下面的文字
  33. ->setTextColor(new Color(0, 0, 0)); //文字的颜色
  34. }
  35. /**
  36. * 生成二维码
  37. * @param string $url [链接]
  38. * @return string [type] [返回图片path]
  39. */
  40. public function create(string $url,string $fileName)
  41. {
  42. $writer = new PngWriter();
  43. $qrCode = QrCodeQrCode::create($url)//跳转的url地址
  44. ->setEncoding(new Encoding('UTF-8')) //设置编码格式
  45. ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow()) //设置纠错级别为低
  46. ->setSize($this->size) //大小
  47. ->setMargin(30) //边距
  48. ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin()) //设置圆轮大小边距
  49. ->setForegroundColor(new Color(0, 0, 0)) //前景色
  50. ->setBackgroundColor(new Color(255, 255, 255)); //背景色
  51. $result = $writer->write($qrCode, $this->logo, $this->label);
  52. $result->getString();
  53. $file_path = public_path() . "/storage/qrcode/";
  54. if (!is_dir($file_path)) {
  55. mkdir($file_path, 0755, true);
  56. }
  57. if (!empty($fileName)){
  58. $qrcode = $fileName.'.png';
  59. }else{
  60. $qrcode = time() . mt_rand(0, 9999). '.png';
  61. }
  62. $result->saveToFile($file_path . $qrcode);
  63. return $file_path . $qrcode;
  64. }
  65. }