QRCodeReader.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. <?php
  2. /*
  3. * Copyright 2007 ZXing authors
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Zxing\Qrcode;
  18. use Zxing\BinaryBitmap;
  19. use Zxing\ChecksumException;
  20. use Zxing\Common\BitMatrix;
  21. use Zxing\FormatException;
  22. use Zxing\NotFoundException;
  23. use Zxing\Qrcode\Decoder\Decoder;
  24. use Zxing\Qrcode\Detector\Detector;
  25. use Zxing\Reader;
  26. use Zxing\Result;
  27. /**
  28. * This implementation can detect and decode QR Codes in an image.
  29. *
  30. * @author Sean Owen
  31. */
  32. class QRCodeReader implements Reader
  33. {
  34. private static array $NO_POINTS = [];
  35. private readonly \Zxing\Qrcode\Decoder\Decoder $decoder;
  36. public function __construct()
  37. {
  38. $this->decoder = new Decoder();
  39. }
  40. /**
  41. * @param null $hints
  42. *
  43. * @return Result
  44. * @throws \Zxing\FormatException
  45. * @throws \Zxing\NotFoundException
  46. */
  47. public function decode(BinaryBitmap $image, $hints = null)
  48. {
  49. $decoderResult = null;
  50. if ($hints !== null && $hints['PURE_BARCODE']) {
  51. $bits = self::extractPureBits($image->getBlackMatrix());
  52. $decoderResult = $this->decoder->decode($bits, $hints);
  53. $points = self::$NO_POINTS;
  54. } else {
  55. $detector = new Detector($image->getBlackMatrix());
  56. $detectorResult = $detector->detect($hints);
  57. $decoderResult = $this->decoder->decode($detectorResult->getBits(), $hints);
  58. $points = $detectorResult->getPoints();
  59. }
  60. $result = new Result($decoderResult->getText(), $decoderResult->getRawBytes(), $points, 'QR_CODE');//BarcodeFormat.QR_CODE
  61. $byteSegments = $decoderResult->getByteSegments();
  62. if ($byteSegments !== null) {
  63. $result->putMetadata('BYTE_SEGMENTS', $byteSegments);//ResultMetadataType.BYTE_SEGMENTS
  64. }
  65. $ecLevel = $decoderResult->getECLevel();
  66. if ($ecLevel !== null) {
  67. $result->putMetadata('ERROR_CORRECTION_LEVEL', $ecLevel);//ResultMetadataType.ERROR_CORRECTION_LEVEL
  68. }
  69. if ($decoderResult->hasStructuredAppend()) {
  70. $result->putMetadata(
  71. 'STRUCTURED_APPEND_SEQUENCE',//ResultMetadataType.STRUCTURED_APPEND_SEQUENCE
  72. $decoderResult->getStructuredAppendSequenceNumber()
  73. );
  74. $result->putMetadata(
  75. 'STRUCTURED_APPEND_PARITY',//ResultMetadataType.STRUCTURED_APPEND_PARITY
  76. $decoderResult->getStructuredAppendParity()
  77. );
  78. }
  79. return $result;
  80. }
  81. /**
  82. * Locates and decodes a QR code in an image.
  83. *
  84. * @return a String representing the content encoded by the QR code
  85. * @throws NotFoundException if a QR code cannot be found
  86. * @throws FormatException if a QR code cannot be decoded
  87. * @throws ChecksumException if error correction fails
  88. */
  89. /**
  90. * This method detects a code in a "pure" image -- that is, pure monochrome image
  91. * which contains only an unrotated, unskewed, image of a code, with some white border
  92. * around it. This is a specialized method that works exceptionally fast in this special
  93. * case.
  94. *
  95. * @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix)
  96. */
  97. private static function extractPureBits(BitMatrix $image)
  98. {
  99. $leftTopBlack = $image->getTopLeftOnBit();
  100. $rightBottomBlack = $image->getBottomRightOnBit();
  101. if ($leftTopBlack === null || $rightBottomBlack == null) {
  102. throw NotFoundException::getNotFoundInstance();
  103. }
  104. $moduleSize = self::moduleSize($leftTopBlack, $image);
  105. $top = $leftTopBlack[1];
  106. $bottom = $rightBottomBlack[1];
  107. $left = $leftTopBlack[0];
  108. $right = $rightBottomBlack[0];
  109. // Sanity check!
  110. if ($left >= $right || $top >= $bottom) {
  111. throw NotFoundException::getNotFoundInstance();
  112. }
  113. if ($bottom - $top != $right - $left) {
  114. // Special case, where bottom-right module wasn't black so we found something else in the last row
  115. // Assume it's a square, so use height as the width
  116. $right = $left + ($bottom - $top);
  117. }
  118. $matrixWidth = round(($right - $left + 1) / $moduleSize);
  119. $matrixHeight = round(($bottom - $top + 1) / $moduleSize);
  120. if ($matrixWidth <= 0 || $matrixHeight <= 0) {
  121. throw NotFoundException::getNotFoundInstance();
  122. }
  123. if ($matrixHeight != $matrixWidth) {
  124. // Only possibly decode square regions
  125. throw NotFoundException::getNotFoundInstance();
  126. }
  127. // Push in the "border" by half the module width so that we start
  128. // sampling in the middle of the module. Just in case the image is a
  129. // little off, this will help recover.
  130. $nudge = (int)($moduleSize / 2.0);// $nudge = (int) ($moduleSize / 2.0f);
  131. $top += $nudge;
  132. $left += $nudge;
  133. // But careful that this does not sample off the edge
  134. // "right" is the farthest-right valid pixel location -- right+1 is not necessarily
  135. // This is positive by how much the inner x loop below would be too large
  136. $nudgedTooFarRight = $left + (int)(($matrixWidth - 1) * $moduleSize) - $right;
  137. if ($nudgedTooFarRight > 0) {
  138. if ($nudgedTooFarRight > $nudge) {
  139. // Neither way fits; abort
  140. throw NotFoundException::getNotFoundInstance();
  141. }
  142. $left -= $nudgedTooFarRight;
  143. }
  144. // See logic above
  145. $nudgedTooFarDown = $top + (int)(($matrixHeight - 1) * $moduleSize) - $bottom;
  146. if ($nudgedTooFarDown > 0) {
  147. if ($nudgedTooFarDown > $nudge) {
  148. // Neither way fits; abort
  149. throw NotFoundException::getNotFoundInstance();
  150. }
  151. $top -= $nudgedTooFarDown;
  152. }
  153. // Now just read off the bits
  154. $bits = new BitMatrix($matrixWidth, $matrixHeight);
  155. for ($y = 0; $y < $matrixHeight; $y++) {
  156. $iOffset = $top + (int)($y * $moduleSize);
  157. for ($x = 0; $x < $matrixWidth; $x++) {
  158. if ($image->get($left + (int)($x * $moduleSize), $iOffset)) {
  159. $bits->set($x, $y);
  160. }
  161. }
  162. }
  163. return $bits;
  164. }
  165. private static function moduleSize($leftTopBlack, BitMatrix $image)
  166. {
  167. $height = $image->getHeight();
  168. $width = $image->getWidth();
  169. $x = $leftTopBlack[0];
  170. $y = $leftTopBlack[1];
  171. /*$x = $leftTopBlack[0];
  172. $y = $leftTopBlack[1];*/
  173. $inBlack = true;
  174. $transitions = 0;
  175. while ($x < $width && $y < $height) {
  176. if ($inBlack != $image->get($x, $y)) {
  177. if (++$transitions == 5) {
  178. break;
  179. }
  180. $inBlack = !$inBlack;
  181. }
  182. $x++;
  183. $y++;
  184. }
  185. if ($x == $width || $y == $height) {
  186. throw NotFoundException::getNotFoundInstance();
  187. }
  188. return ($x - $leftTopBlack[0]) / 7.0; //return ($x - $leftTopBlack[0]) / 7.0f;
  189. }
  190. public function reset(): void
  191. {
  192. // do nothing
  193. }
  194. final protected function getDecoder()
  195. {
  196. return $this->decoder;
  197. }
  198. }