QRImageWithLogo.php 2.1 KB

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