svgWithLogoAndCustomShapes.php 6.0 KB

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