QRImageWithLogo.php 2.2 KB

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