QRImageWithLogo.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * Class QRImageWithLogo
  4. *
  5. * @filesource QRImageWithLogo.php
  6. * @created 18.11.2020
  7. * @package chillerlan\QRCodeExamples
  8. * @author smiley <smiley@chillerlan.net>
  9. * @copyright 2020 smiley
  10. * @license MIT
  11. *
  12. * @noinspection PhpComposerExtensionStubsInspection
  13. */
  14. use chillerlan\QRCode\Output\{QRCodeOutputException, QRImage};
  15. use function imagecopyresampled, imagecreatefrompng, imagesx, imagesy, is_file, is_readable;
  16. class QRImageWithLogo extends QRImage{
  17. /**
  18. * @param string|null $file
  19. * @param string|null $logo
  20. *
  21. * @return string
  22. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  23. */
  24. public function dump(string $file = null, string $logo = null):string{
  25. // set returnResource to true to skip further processing for now
  26. $this->options->returnResource = true;
  27. // of course you could accept other formats too (such as resource or Imagick)
  28. // i'm not checking for the file type either for simplicity reasons (assuming PNG)
  29. if(!is_file($logo) || !is_readable($logo)){
  30. throw new QRCodeOutputException('invalid logo');
  31. }
  32. $this->matrix->setLogoSpace(
  33. $this->options->logoSpaceWidth,
  34. $this->options->logoSpaceHeight
  35. // not utilizing the position here
  36. );
  37. // there's no need to save the result of dump() into $this->image here
  38. parent::dump($file);
  39. $im = imagecreatefrompng($logo);
  40. // get logo image size
  41. $w = imagesx($im);
  42. $h = imagesy($im);
  43. // set new logo size, leave a border of 1 module (no proportional resize/centering)
  44. $lw = ($this->options->logoSpaceWidth - 2) * $this->options->scale;
  45. $lh = ($this->options->logoSpaceHeight - 2) * $this->options->scale;
  46. // get the qrcode size
  47. $ql = $this->matrix->size() * $this->options->scale;
  48. // scale the logo and copy it over. done!
  49. imagecopyresampled($this->image, $im, ($ql - $lw) / 2, ($ql - $lh) / 2, 0, 0, $lw, $lh, $w, $h);
  50. $imageData = $this->dumpImage();
  51. if($file !== null){
  52. $this->saveToFile($imageData, $file);
  53. }
  54. if($this->options->imageBase64){
  55. $imageData = 'data:image/'.$this->options->outputType.';base64,'.base64_encode($imageData);
  56. }
  57. return $imageData;
  58. }
  59. }