svgWithLogoAndCustomShapes.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. <?php
  2. /**
  3. * SVG with logo and custom shapes example
  4. *
  5. * @see https://github.com/chillerlan/php-qrcode/discussions/150
  6. *
  7. * @created 05.03.2022
  8. * @author smiley <smiley@chillerlan.net>
  9. * @copyright 2022 smiley
  10. * @license MIT
  11. *
  12. * @noinspection PhpComposerExtensionStubsInspection
  13. */
  14. declare(strict_types=1);
  15. use chillerlan\QRCode\{QRCode, QRCodeException, QROptions};
  16. use chillerlan\QRCode\Common\EccLevel;
  17. use chillerlan\QRCode\Data\QRMatrix;
  18. use chillerlan\QRCode\Output\QRMarkupSVG;
  19. require_once __DIR__.'/../vendor/autoload.php';
  20. /*
  21. * Class definition
  22. */
  23. /**
  24. * Create SVG QR Codes with embedded logos (that are also SVG)
  25. */
  26. class QRSvgWithLogoAndCustomShapes extends QRMarkupSVG{
  27. protected function paths():string{
  28. // make sure connect paths is enabled
  29. $this->options->connectPaths = true;
  30. // we're calling QRMatrix::setLogoSpace() manually, so QROptions::$addLogoSpace has no effect here
  31. $this->matrix->setLogoSpace((int)ceil($this->moduleCount * $this->options->svgLogoScale));
  32. // generate the path element(s) - in this case it's just one element as we've "disabled" several options
  33. $svg = parent::paths();
  34. // add the custom shapes for the finder patterns
  35. $svg .= $this->getFinderPatterns();
  36. // and add the custom logo
  37. $svg .= $this->getLogo();
  38. return $svg;
  39. }
  40. protected function path(string $path, int $M_TYPE):string{
  41. // omit the "fill" and "opacity" attributes on the path element
  42. return sprintf('<path class="%s" d="%s"/>', $this->getCssClass($M_TYPE), $path);
  43. }
  44. /**
  45. * returns a path segment for a single module
  46. *
  47. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d
  48. */
  49. protected function module(int $x, int $y, int $M_TYPE):string{
  50. if(
  51. !$this->matrix->isDark($M_TYPE)
  52. // we're skipping the finder patterns here
  53. || $this->matrix->checkType($x, $y, QRMatrix::M_FINDER)
  54. || $this->matrix->checkType($x, $y, QRMatrix::M_FINDER_DOT)
  55. ){
  56. return '';
  57. }
  58. // return a heart shape (or any custom shape for that matter)
  59. return sprintf('M%1$s %2$s m0.5,0.96 l-0.412,-0.412 a0.3 0.3 0 0 1 0.412,-0.435 a0.3 0.3 0 0 1 0.412,0.435Z', $x, $y);
  60. }
  61. /**
  62. * returns a custom path for the 3 finder patterns
  63. */
  64. protected function getFinderPatterns():string{
  65. $qz = ($this->options->addQuietzone) ? $this->options->quietzoneSize : 0;
  66. // the positions for the finder patterns (top left corner)
  67. // $this->moduleCount includes 2* the quiet zone size already, so we need to take this into account
  68. $pos = [
  69. [(0 + $qz), (0 + $qz)],
  70. [(0 + $qz), ($this->moduleCount - $qz - 7)],
  71. [($this->moduleCount - $qz - 7), (0 + $qz)],
  72. ];
  73. // the custom path for one finder pattern - the first move (M) is parametrized, the rest are relative coordinates
  74. $path = 'M%1$s,%2$s m2,0 h3 q2,0 2,2 v3 q0,2 -2,2 h-3 q-2,0 -2,-2 v-3 q0,-2 2,-2z m0,1 q-1,0 -1,1 v3 '.
  75. 'q0,1 1,1 h3 q1,0 1,-1 v-3 q0,-1 -1,-1z m0,2.5 a1.5,1.5 0 1 0 3,0 a1.5,1.5 0 1 0 -3,0Z';
  76. $finder = [];
  77. foreach($pos as [$ix, $iy]){
  78. $finder[] = sprintf($path, $ix, $iy);
  79. }
  80. return sprintf(
  81. '%s<path class="%s" d="%s"/>',
  82. $this->options->eol,
  83. $this->getCssClass(QRMatrix::M_FINDER_DARK),
  84. implode(' ', $finder),
  85. );
  86. }
  87. /**
  88. * returns a <g> element that contains the SVG logo and positions it properly within the QR Code
  89. *
  90. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g
  91. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
  92. */
  93. protected function getLogo():string{
  94. // @todo: customize the <g> element to your liking (css class, style...)
  95. return sprintf(
  96. '%5$s<g transform="translate(%1$s %1$s) scale(%2$s)" class="%3$s">%5$s %4$s%5$s</g>',
  97. (($this->moduleCount - ($this->moduleCount * $this->options->svgLogoScale)) / 2),
  98. $this->options->svgLogoScale,
  99. $this->options->svgLogoCssClass,
  100. file_get_contents($this->options->svgLogo),
  101. $this->options->eol,
  102. );
  103. }
  104. }
  105. /**
  106. * augment the QROptions class
  107. *
  108. * @property string $svgLogo
  109. * @property float $svgLogoScale
  110. * @property string $svgLogoCssClass
  111. */
  112. class SVGWithLogoAndCustomShapesOptions extends QROptions{
  113. // path to svg logo
  114. protected string $svgLogo;
  115. // logo scale in % of QR Code size, clamped to 10%-30%
  116. protected float $svgLogoScale = 0.20;
  117. // css class for the logo (defined in $svgDefs)
  118. protected string $svgLogoCssClass = '';
  119. // check logo
  120. protected function set_svgLogo(string $svgLogo):void{
  121. if(!file_exists($svgLogo) || !is_readable($svgLogo)){
  122. throw new QRCodeException('invalid svg logo');
  123. }
  124. // @todo: validate svg
  125. $this->svgLogo = $svgLogo;
  126. }
  127. // clamp logo scale
  128. protected function set_svgLogoScale(float $svgLogoScale):void{
  129. $this->svgLogoScale = max(0.05, min(0.3, $svgLogoScale));
  130. }
  131. }
  132. /*
  133. * Runtime
  134. */
  135. // please excuse the IDE yelling https://youtrack.jetbrains.com/issue/WI-66549
  136. $options = new SVGWithLogoAndCustomShapesOptions;
  137. // SVG logo options (see extended class below)
  138. $options->svgLogo = __DIR__.'/github.svg'; // logo from: https://github.com/simple-icons/simple-icons
  139. $options->svgLogoScale = 0.25;
  140. $options->svgLogoCssClass = 'qr-logo dark';
  141. // QROptions
  142. $options->version = 5;
  143. $options->quietzoneSize = 4;
  144. $options->outputInterface = QRSvgWithLogoAndCustomShapes::class;
  145. $options->outputBase64 = false;
  146. $options->eccLevel = EccLevel::H; // ECC level H is required when using logos
  147. $options->addQuietzone = true;
  148. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/linearGradient
  149. $options->svgDefs = '
  150. <linearGradient id="gradient" x1="100%" y2="100%">
  151. <stop stop-color="#D70071" offset="0"/>
  152. <stop stop-color="#9C4E97" offset="0.5"/>
  153. <stop stop-color="#0035A9" offset="1"/>
  154. </linearGradient>
  155. <style><![CDATA[
  156. .dark{fill: url(#gradient);}
  157. .qr-logo{fill: #424242;}
  158. ]]></style>';
  159. $out = (new QRCode($options))->render('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  160. if(PHP_SAPI !== 'cli'){
  161. header('Content-type: image/svg+xml');
  162. if(extension_loaded('zlib')){
  163. header('Vary: Accept-Encoding');
  164. header('Content-Encoding: gzip');
  165. $out = gzencode($out, 9);
  166. }
  167. }
  168. echo $out;
  169. exit;