Advanced-usage.md.txt 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # Advanced usage
  2. ## Configuration via `QROptions`
  3. The [`QROptions`](https://github.com/chillerlan/php-qrcode/blob/main/src/QROptions.php) class is a container based on [chillerlan/php-settings-container](https://github.com/chillerlan/php-settings-container) that behaves similar to a [`\stdClass`](https://www.php.net/manual/class.stdclass) object, but with fixed properties.
  4. A list with all available `QROptions` can be found under [configuration settings](../Usage/Configuration-settings.md).
  5. ```php
  6. $options = new QROptions;
  7. // set some values
  8. $options->version = 7; // property "version" exists
  9. $options->foo = 'bar'; // property "foo" does not exist (and will not be created)
  10. // retrieve values
  11. var_dump($options->version); // -> 7
  12. var_dump($options->foo); // -> null (no error will be thrown)
  13. ```
  14. ### Supply an `iterable` of options
  15. The constructor takes an `iterable` of `$key => $value` pairs. For each setting an optional setter will be called if present.
  16. ```php
  17. $myOptions = [
  18. 'version' => 5,
  19. 'outputType' => QROutputInterface::GDIMAGE_PNG,
  20. 'eccLevel' => EccLevel::M,
  21. ];
  22. $options = new QROptions($myOptions);
  23. ```
  24. You can also set an `iterable` of options on an existing QROptions instance:
  25. ```php
  26. $options->fromIterable($myOptions);
  27. ```
  28. In addition to that, you can also supply the `iterable` of option values directly to the `QRCode` constructor (v6+):
  29. ```php
  30. $qrCode = new QRCode($myOptions);
  31. ```
  32. ### Load and save options from/to JSON
  33. The settings can be saved to and loaded from JSON, e.g. to store them in a database:
  34. ```php
  35. $json = $options->toJSON(JSON_THROW_ON_ERROR);
  36. // via JsonSerializable interface
  37. $json = json_encode($options, JSON_THROW_ON_ERROR);
  38. // via __toString()
  39. $json = (string)$options;
  40. $options = (new QROptions)->fromJSON($json);
  41. // on an existing instance - properties will be overwriten
  42. $options->fromJSON($json);
  43. ```
  44. ### Extending the `QROptions` class
  45. In case you need additional settings for your output module, just extend `QROptions`...
  46. ```php
  47. class MyCustomOptions extends QROptions{
  48. protected string $myParam = 'defaultValue';
  49. // ...
  50. }
  51. ```
  52. ...or use the [`SettingsContainerInterface`](https://github.com/chillerlan/php-settings-container/blob/main/src/SettingsContainerInterface.php), which is the more flexible approach.
  53. ```php
  54. trait MyCustomOptionsTrait{
  55. protected string $myParam = 'defaultValue';
  56. // ...
  57. // an optional magic setter, named "set_" + property name
  58. protected function set_myParam(string $myParam):void{
  59. $this->myParam = trim($myParam);
  60. }
  61. // an optional magic getter, named "get_" + property name
  62. protected function get_myParam():string{
  63. return strtoupper($this->myParam);
  64. }
  65. }
  66. class MyCustomOptions extends SettingsContainerAbstract{
  67. use QROptionsTrait, MyCustomOptionsTrait;
  68. }
  69. // set the options
  70. $myCustomOptions = new MyCustomOptions;
  71. $myCustomOptions->myParam = 'whatever value';
  72. ```
  73. Extend the `SettingsContainerInterface` on-the-fly:
  74. ```php
  75. $myOptions = [
  76. 'myParam' => 'whatever value',
  77. // ...
  78. ];
  79. $myCustomOptions = new class($myOptions) extends SettingsContainerAbstract{
  80. use QROptionsTrait, MyCustomOptionsTrait;
  81. };
  82. ```
  83. ## `QRCode` methods
  84. Aside of invoking a `QRCode` instance with an optional `QROptions` object as parameter, you can also set the options instance after invocation.
  85. After invocation of the `QROptions` instance, values can be set without calling `QRCode::setOptions()` again (instance is backreferenced), however, this may create side effects.
  86. ```php
  87. // instance will be invoked with default settings
  88. $qrcode = new QRCode;
  89. // set options after QRCode invocation
  90. $options = new QROptions;
  91. $qrcode->setOptions($options);
  92. ```
  93. ### Render a `QRMatrix` instance
  94. You can render a [`QRMatrix`](https://github.com/chillerlan/php-qrcode/blob/main/src/Data/QRMatrix.php) instance directly:
  95. ```php
  96. // a matrix from the current data segments
  97. $matrix = $qrcode->getQRMatrix();
  98. // from the QR Code reader
  99. $matrix = $readerResult->getQRMatrix();
  100. // manually invoked
  101. $matrix = (new QRMatrix(new Version(7), new EccLevel(EccLevel::M)))->initFunctionalPatterns();
  102. $output = $qrcode->renderMatrix($matrix);
  103. // save to file
  104. $qrcode->renderMatrix($matrix, '/path/to/qrcode.svg');
  105. ```
  106. ### Mixed mode
  107. Mixed mode QR Codes can be generated by adding several data segments:
  108. ```php
  109. // make sure to set a proper internal encoding character set
  110. // ideally, this should be set in php.ini internal_encoding,
  111. // default_charset or mbstring.internal_encoding
  112. mb_internal_encoding('UTF-8');
  113. // clear any existing data segments
  114. $qrcode->clearSegments();
  115. $qrcode
  116. ->addNumericSegment($numericData)
  117. ->addAlphaNumSegment($alphaNumData)
  118. ->addKanjiSegment($kanjiData)
  119. ->addHanziSegment($hanziData)
  120. ->addByteSegment($binaryData)
  121. ->addEciSegment(ECICharset::GB18030, $encodedEciData)
  122. ;
  123. $output = $qrcode->render();
  124. // render to file
  125. $qrcode->render(null, '/path/to/qrcode.svg');
  126. ```
  127. The [`QRDataModeInterface`](https://github.com/chillerlan/php-qrcode/blob/main/src/Data/QRDataModeInterface.php) offers the `validateString()` method (implemended for `AlphaNum`, `Byte`, `Hanzi`, `Kanji` and `Number`).
  128. This method is used internally when a data mode is invoked, but it can come in handy if you need to check input data beforehand.
  129. ```php
  130. if(!Hanzi::validateString($data)){
  131. throw new Exception('invalid GB2312 data');
  132. }
  133. $qrcode->addHanziSegment($data);
  134. ```
  135. ### QR Code reader
  136. In some cases it might be necessary to increase the contrast of a QR Code image:
  137. ```php
  138. $options->readerUseImagickIfAvailable = true;
  139. $options->readerIncreaseContrast = true;
  140. $options->readerGrayscale = true;
  141. $qrcode = new QRCode($options);
  142. $result = $qrcode->readFromFile('path/to/qrcode.png');
  143. $result = $qrcode->readFromBlob($imagedata);
  144. ```
  145. The `QRMatrix` object from the [`DecoderResult`](https://github.com/chillerlan/php-qrcode/blob/main/src/Decoder/DecoderResult.php) can be reused:
  146. ```php
  147. $matrix = $result->getQRMatrix();
  148. // ...matrix modification...
  149. $output = (new QRCode($options))->renderMatrix($matrix);
  150. // ...output
  151. ```
  152. ## Common output options
  153. ### Save to file
  154. You can specify an output file path in which the QR Code content is stored:
  155. ```php
  156. $options->outputBase64 = false;
  157. $options->cachefile = '/path/to/qrcode.svg';
  158. $qrcode->render($data);
  159. printf('<img src="%s" alt="QR Code" />', $options->cachefile);
  160. ```
  161. The file path can also be supplied as second parameter to the render methods (this will override the `QROptions::$cachefile` setting):
  162. ```php
  163. $qrcode->render($data, '/path/to/qrcode.svg');
  164. ```
  165. ### Base64 URI output
  166. By default, a [Base64 encoded data URI](https://en.wikipedia.org/wiki/Data_URI_scheme) will be returned (where applicable):
  167. ```php
  168. echo $qrcode->render($data); // -> data:image/png;base64,...
  169. ```
  170. Disable Base64 output:
  171. ```php
  172. $options->outputBase64 = false;
  173. header('Content-type: image/png');
  174. echo $qrcode->render($data);
  175. ```
  176. ### Return the image resource
  177. In some cases you might want to modify the QR image after creation (without crating a custom output class), in which case you want the internal image resource rather than the final output.
  178. ```php
  179. $options->outputInterface = QRImagick::class;
  180. $options->returnResource = true;
  181. /** @var Imagick $imagick */
  182. $imagick = $qrcode->render($data);
  183. echo $imagick->getImageBlob();
  184. ```
  185. ### Add a logo space
  186. ```php
  187. $options->addLogoSpace = true;
  188. $options->logoSpaceWidth = 9;
  189. $options->logoSpaceHeight = 9;
  190. $options->logoSpaceStartX = 10;
  191. $options->logoSpaceStartY = 10;
  192. ```