QrController.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace addons\RfDevTool\backend\controllers;
  3. use Yii;
  4. use yii\web\Response;
  5. use Da\QrCode\QrCode;
  6. use Da\QrCode\Label;
  7. use addons\RfDevTool\common\models\QrForm;
  8. use common\helpers\StringHelper;
  9. use yii\web\UnprocessableEntityHttpException;
  10. /**
  11. * Class QrController
  12. * @package addons\RfDevTool\backend\controllers
  13. * @author jianyan74 <751393839@qq.com>
  14. */
  15. class QrController extends BaseController
  16. {
  17. /**
  18. * @return string
  19. */
  20. public function actionIndex()
  21. {
  22. $model = new QrForm();
  23. $model->content = Yii::$app->request->hostInfo;
  24. return $this->render('index', [
  25. 'model' => $model
  26. ]);
  27. }
  28. /**
  29. * @return string
  30. * @throws UnprocessableEntityHttpException
  31. * @throws \Da\QrCode\Exception\InvalidPathException
  32. * @throws \yii\base\InvalidConfigException
  33. */
  34. public function actionCreate()
  35. {
  36. $model = new QrForm();
  37. $model->load(Yii::$app->request->get());
  38. if (!$model->validate()) {
  39. throw new UnprocessableEntityHttpException($this->getError($model));
  40. }
  41. /** @var \Da\QrCode\Component\QrCodeComponent $qr */
  42. $qr = Yii::$app->get('qr');
  43. Yii::$app->response->format = Response::FORMAT_RAW;
  44. Yii::$app->response->headers->add('Content-Type', $qr->getContentType());
  45. $label = new Label(
  46. $model->label,
  47. $font = null,
  48. $fontSize = $model->label_size,
  49. $alignment = $model->label_location,
  50. $margins = [
  51. 't' => 0,
  52. 'r' => 10,
  53. 'b' => 10,
  54. 'l' => 10,
  55. ]
  56. );
  57. // 前景色
  58. list($f_r, $f_g, $f_b) = sscanf($model->foreground, "#%02x%02x%02x");
  59. // 背景色
  60. list($b_r, $b_g, $b_b) = sscanf($model->background, "#%02x%02x%02x");
  61. $data = (new QrCode($model->content))
  62. ->useForegroundColor($f_r, $f_g, $f_b)
  63. ->useBackgroundColor($b_r, $b_g, $b_b)
  64. ->useEncoding('UTF-8');
  65. if (!empty($model->logo)) {
  66. $localFilePath = StringHelper::getLocalFilePath($model->logo);
  67. $data = $data->useLogo($localFilePath);
  68. }
  69. $data = $data
  70. ->setErrorCorrectionLevel($model->error_correction_level)
  71. ->setLogoWidth($model->logo_size)
  72. ->setSize($model->size)
  73. ->setMargin($model->margin);
  74. if (!empty($model->label_size) && !empty($model->label)) {
  75. $data = $data->setLabel($label);
  76. }
  77. // $data->writeFile(__DIR__ . '/codes/my-code.png');
  78. return $data->writeString();
  79. }
  80. }
粤ICP备19079148号