QRImageWithLogo.php 1.9 KB

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