svgWithLogoAndCustomShapes.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. // add the custom shapes for the finder patterns
  37. $svg .= $this->getFinderPatterns();
  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->isDark($M_TYPE)
  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 sprintf(
  86. '%s<path class="%s" d="%s"/>',
  87. $this->options->eol,
  88. $this->getCssClass(QRMatrix::M_FINDER_DARK),
  89. implode(' ', $finder)
  90. );
  91. }
  92. /**
  93. * returns a <g> element that contains the SVG logo and positions it properly within the QR Code
  94. *
  95. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g
  96. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
  97. */
  98. protected function getLogo():string{
  99. // @todo: customize the <g> element to your liking (css class, style...)
  100. return sprintf(
  101. '%5$s<g transform="translate(%1$s %1$s) scale(%2$s)" class="%3$s">%5$s %4$s%5$s</g>',
  102. (($this->moduleCount - ($this->moduleCount * $this->options->svgLogoScale)) / 2),
  103. $this->options->svgLogoScale,
  104. $this->options->svgLogoCssClass,
  105. file_get_contents($this->options->svgLogo),
  106. $this->options->eol
  107. );
  108. }
  109. }
  110. /**
  111. * augment the QROptions class
  112. */
  113. class SVGWithLogoAndCustomShapesOptions extends QROptions{
  114. // path to svg logo
  115. protected string $svgLogo;
  116. // logo scale in % of QR Code size, clamped to 10%-30%
  117. protected float $svgLogoScale = 0.20;
  118. // css class for the logo (defined in $svgDefs)
  119. protected string $svgLogoCssClass = '';
  120. // check logo
  121. protected function set_svgLogo(string $svgLogo):void{
  122. if(!file_exists($svgLogo) || !is_readable($svgLogo)){
  123. throw new QRCodeException('invalid svg logo');
  124. }
  125. // @todo: validate svg
  126. $this->svgLogo = $svgLogo;
  127. }
  128. // clamp logo scale
  129. protected function set_svgLogoScale(float $svgLogoScale):void{
  130. $this->svgLogoScale = max(0.05, min(0.3, $svgLogoScale));
  131. }
  132. }
  133. /*
  134. * Runtime
  135. */
  136. // please excuse the IDE yelling https://youtrack.jetbrains.com/issue/WI-66549
  137. $options = new SVGWithLogoAndCustomShapesOptions;
  138. // SVG logo options (see extended class below)
  139. $options->svgLogo = __DIR__.'/github.svg'; // logo from: https://github.com/simple-icons/simple-icons
  140. $options->svgLogoScale = 0.25;
  141. $options->svgLogoCssClass = 'qr-logo dark';
  142. // QROptions
  143. $options->version = 5;
  144. $options->quietzoneSize = 4;
  145. $options->outputType = QROutputInterface::CUSTOM;
  146. $options->outputInterface = QRSvgWithLogoAndCustomShapes::class;
  147. $options->outputBase64 = false;
  148. $options->eccLevel = EccLevel::H; // ECC level H is required when using logos
  149. $options->addQuietzone = true;
  150. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/linearGradient
  151. $options->svgDefs = '
  152. <linearGradient id="gradient" x1="100%" y2="100%">
  153. <stop stop-color="#D70071" offset="0"/>
  154. <stop stop-color="#9C4E97" offset="0.5"/>
  155. <stop stop-color="#0035A9" offset="1"/>
  156. </linearGradient>
  157. <style><![CDATA[
  158. .dark{fill: url(#gradient);}
  159. .qr-logo{fill: #424242;}
  160. ]]></style>';
  161. $out = (new QRCode($options))->render('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  162. if(php_sapi_name() !== 'cli'){
  163. header('Content-type: image/svg+xml');
  164. if(extension_loaded('zlib')){
  165. header('Vary: Accept-Encoding');
  166. header('Content-Encoding: gzip');
  167. $out = gzencode($out, 9);
  168. }
  169. }
  170. echo $out;
  171. exit;