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