diff --git a/.gitignore b/.gitignore index 716b1f6..3775e9f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,6 @@ /vendor .idea/ .phpunit.result.cache + +tests/qrcodes/private_test.png +tests/qrcodes/private_test2.png \ No newline at end of file diff --git a/README.md b/README.md index 75c7735..870cc21 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,8 @@ # QR code decoder / reader for PHP + +[![Tests](https://github.com/khanamiryan/php-qrcode-detector-decoder/actions/workflows/tests.yml/badge.svg)](https://github.com/khanamiryan/php-qrcode-detector-decoder/actions/workflows/tests.yml) +[![Static Tests](https://github.com/khanamiryan/php-qrcode-detector-decoder/actions/workflows/static_tests.yml/badge.svg)](https://github.com/khanamiryan/php-qrcode-detector-decoder/actions/workflows/static_tests.yml) + This is a PHP library to detect and decode QR-codes.
This is first and only QR code reader that works without extensions.
Ported from [ZXing library](https://github.com/zxing/zxing) diff --git a/lib/Common/HybridBinarizer.php b/lib/Common/HybridBinarizer.php index 638c53c..a0d6e3d 100644 --- a/lib/Common/HybridBinarizer.php +++ b/lib/Common/HybridBinarizer.php @@ -146,7 +146,7 @@ private static function calculateBlackPoints( // finish the rest of the rows quickly for ($yy++, $offset += $width; $yy < self::$BLOCK_SIZE; $yy++, $offset += $width) { for ($xx = 0; $xx < self::$BLOCK_SIZE; $xx++) { - $sum += ($luminances[$offset + $xx] & 0xFF); + $sum += (((int)$luminances[(int)round($offset + $xx)]) & 0xFF); } } } @@ -266,7 +266,7 @@ private static function thresholdBlock( for ($y = 0, $offset = $yoffset * $stride + $xoffset; $y < self::$BLOCK_SIZE; $y++, $offset += $stride) { for ($x = 0; $x < self::$BLOCK_SIZE; $x++) { // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0. - if (($luminances[$offset + $x] & 0xFF) <= $threshold) { + if (($luminances[(int)round($offset + $x)] & 0xFF) <= $threshold) { $matrix->set($xoffset + $x, $yoffset + $y); } } diff --git a/lib/Common/PerspectiveTransform.php b/lib/Common/PerspectiveTransform.php index e02fbbc..dd8e586 100644 --- a/lib/Common/PerspectiveTransform.php +++ b/lib/Common/PerspectiveTransform.php @@ -173,8 +173,11 @@ public function transformPoints(array &$points, &$yValues = 0): void $x = $points[$i]; $y = $points[$i + 1]; $denominator = $a13 * $x + $a23 * $y + $a33; - $points[$i] = ($a11 * $x + $a21 * $y + $a31) / $denominator; - $points[$i + 1] = ($a12 * $x + $a22 * $y + $a32) / $denominator; + // TODO: think what we do if $denominator == 0 (division by zero) + if ($denominator != 0.0) { + $points[$i] = ($a11 * $x + $a21 * $y + $a31) / $denominator; + $points[$i + 1] = ($a12 * $x + $a22 * $y + $a32) / $denominator; + } } } diff --git a/lib/IMagickLuminanceSource.php b/lib/IMagickLuminanceSource.php index 90fe4cd..f4ef0dc 100644 --- a/lib/IMagickLuminanceSource.php +++ b/lib/IMagickLuminanceSource.php @@ -98,7 +98,7 @@ public function _IMagickLuminanceSource(\Imagick $image, $width, $height): void $image->setImageColorspace(\Imagick::COLORSPACE_GRAY); // Check that we actually have enough space to do it - if ($width * $height * 16 * 3 > $this->kmgStringToBytes(ini_get('memory_limit'))) { + if (ini_get('memory_limit') != -1 && $width * $height * 16 * 3 > $this->kmgStringToBytes(ini_get('memory_limit'))) { throw new \RuntimeException("PHP Memory Limit does not allow pixel export."); } $pixels = $image->exportImagePixels(1, 1, $width, $height, "RGB", \Imagick::PIXEL_CHAR); diff --git a/lib/Qrcode/Decoder/BitMatrixParser.php b/lib/Qrcode/Decoder/BitMatrixParser.php index 27afb73..bc2479d 100644 --- a/lib/Qrcode/Decoder/BitMatrixParser.php +++ b/lib/Qrcode/Decoder/BitMatrixParser.php @@ -42,7 +42,7 @@ public function __construct($bitMatrix) { $dimension = $bitMatrix->getHeight(); if ($dimension < 21 || ($dimension & 0x03) != 1) { - throw FormatException::getFormatInstance(); + throw new FormatException(); } $this->bitMatrix = $bitMatrix; } @@ -108,7 +108,7 @@ public function readCodewords() $readingUp ^= true; // readingUp = !readingUp; // switch directions } if ($resultOffset != $version->getTotalCodewords()) { - throw FormatException::getFormatInstance(); + throw new FormatException(); } return $result; @@ -156,7 +156,7 @@ public function readFormatInformation() if ($parsedFormatInfo != null) { return $parsedFormatInfo; } - throw FormatException::getFormatInstance(); + throw new FormatException(); } /** @@ -221,7 +221,7 @@ public function readVersion() return $theParsedVersion; } - throw FormatException::getFormatInstance("both version information locations cannot be parsed as the valid encoding of version information"); + throw new FormatException("both version information locations cannot be parsed as the valid encoding of version information"); } /** diff --git a/lib/Qrcode/Decoder/DecodedBitStreamParser.php b/lib/Qrcode/Decoder/DecodedBitStreamParser.php index e7a958d..18b283a 100644 --- a/lib/Qrcode/Decoder/DecodedBitStreamParser.php +++ b/lib/Qrcode/Decoder/DecodedBitStreamParser.php @@ -77,7 +77,7 @@ public static function decode( $fc1InEffect = true; } elseif ($mode == Mode::$STRUCTURED_APPEND) { if ($bits->available() < 16) { - throw FormatException::getFormatInstance("Bits available < 16"); + throw new FormatException("Bits available < 16"); } // sequence number and parity is added later to the result metadata // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue @@ -88,7 +88,7 @@ public static function decode( $value = self::parseECIValue($bits); $currentCharacterSetECI = CharacterSetECI::getCharacterSetECIByValue($value); if ($currentCharacterSetECI == null) { - throw FormatException::getFormatInstance("Current character set ECI is null"); + throw new FormatException("Current character set ECI is null"); } } else { // First handle Hanzi mode which does not start with character count @@ -112,7 +112,7 @@ public static function decode( } elseif ($mode == Mode::$KANJI) { self::decodeKanjiSegment($bits, $result, $count); } else { - throw FormatException::getFormatInstance("Unknown mode $mode to decode"); + throw new FormatException("Unknown mode $mode to decode"); } } } @@ -120,7 +120,7 @@ public static function decode( } while ($mode != Mode::$TERMINATOR); } catch (\InvalidArgumentException $e) { // from readBits() calls - throw FormatException::getFormatInstance("Invalid argument exception when formatting: " . $e->getMessage()); + throw new FormatException("Invalid argument exception when formatting: " . $e->getMessage()); } return new DecoderResult( @@ -152,7 +152,7 @@ private static function parseECIValue(BitSource $bits): int return (($firstByte & 0x1F) << 16) | $secondThirdBytes; } - throw FormatException::getFormatInstance("ECI Value parsing failed."); + throw new FormatException("ECI Value parsing failed."); } /** @@ -167,7 +167,7 @@ private static function decodeHanziSegment( ): void { // Don't crash trying to read more bits than we have available. if ($count * 13 > $bits->available()) { - throw FormatException::getFormatInstance("Trying to read more bits than we have available"); + throw new FormatException("Trying to read more bits than we have available"); } // Each character will require 2 bytes. Read the characters as 2-byte pairs @@ -202,36 +202,36 @@ private static function decodeNumericSegment( while ($count >= 3) { // Each 10 bits encodes three digits if ($bits->available() < 10) { - throw FormatException::getFormatInstance("Not enough bits available"); + throw new FormatException("Not enough bits available"); } $threeDigitsBits = $bits->readBits(10); if ($threeDigitsBits >= 1000) { - throw FormatException::getFormatInstance("Too many three digit bits"); + throw new FormatException("Too many three digit bits"); } $result .= (self::toAlphaNumericChar($threeDigitsBits / 100)); - $result .= (self::toAlphaNumericChar(($threeDigitsBits / 10) % 10)); + $result .= (self::toAlphaNumericChar(((int)round($threeDigitsBits / 10)) % 10)); $result .= (self::toAlphaNumericChar($threeDigitsBits % 10)); $count -= 3; } if ($count == 2) { // Two digits left over to read, encoded in 7 bits if ($bits->available() < 7) { - throw FormatException::getFormatInstance("Two digits left over to read, encoded in 7 bits, but only " . $bits->available() . ' bits available'); + throw new FormatException("Two digits left over to read, encoded in 7 bits, but only " . $bits->available() . ' bits available'); } $twoDigitsBits = $bits->readBits(7); if ($twoDigitsBits >= 100) { - throw FormatException::getFormatInstance("Too many bits: $twoDigitsBits expected < 100"); + throw new FormatException("Too many bits: $twoDigitsBits expected < 100"); } $result .= (self::toAlphaNumericChar($twoDigitsBits / 10)); $result .= (self::toAlphaNumericChar($twoDigitsBits % 10)); } elseif ($count == 1) { // One digit left over to read if ($bits->available() < 4) { - throw FormatException::getFormatInstance("One digit left to read, but < 4 bits available"); + throw new FormatException("One digit left to read, but < 4 bits available"); } $digitBits = $bits->readBits(4); if ($digitBits >= 10) { - throw FormatException::getFormatInstance("Too many bits: $digitBits expected < 10"); + throw new FormatException("Too many bits: $digitBits expected < 10"); } $result .= (self::toAlphaNumericChar($digitBits)); } @@ -242,11 +242,12 @@ private static function decodeNumericSegment( */ private static function toAlphaNumericChar(int|float $value) { - if ($value >= count(self::$ALPHANUMERIC_CHARS)) { - throw FormatException::getFormatInstance("$value has too many alphanumeric chars"); + $intVal = (int) $value; + if ($intVal >= count(self::$ALPHANUMERIC_CHARS)) { + throw new FormatException("$intVal is too many alphanumeric chars"); } - return self::$ALPHANUMERIC_CHARS[$value]; + return self::$ALPHANUMERIC_CHARS[(int)($intVal)]; } private static function decodeAlphanumericSegment( @@ -259,7 +260,7 @@ private static function decodeAlphanumericSegment( $start = strlen((string) $result); while ($count > 1) { if ($bits->available() < 11) { - throw FormatException::getFormatInstance("Not enough bits available to read two expected characters"); + throw new FormatException("Not enough bits available to read two expected characters"); } $nextTwoCharsBits = $bits->readBits(11); $result .= (self::toAlphaNumericChar($nextTwoCharsBits / 45)); @@ -269,7 +270,7 @@ private static function decodeAlphanumericSegment( if ($count == 1) { // special case: one character left if ($bits->available() < 6) { - throw FormatException::getFormatInstance("Not enough bits available to read one expected character"); + throw new FormatException("Not enough bits available to read one expected character"); } $result .= self::toAlphaNumericChar($bits->readBits(6)); } @@ -300,7 +301,7 @@ private static function decodeByteSegment( ): void { // Don't crash trying to read more bits than we have available. if (8 * $count > $bits->available()) { - throw FormatException::getFormatInstance("Trying to read more bits than we have available"); + throw new FormatException("Trying to read more bits than we have available"); } $readBytes = fill_array(0, $count, 0); @@ -337,7 +338,7 @@ private static function decodeKanjiSegment( ): void { // Don't crash trying to read more bits than we have available. if ($count * 13 > $bits->available()) { - throw FormatException::getFormatInstance("Trying to read more bits than we have available"); + throw new FormatException("Trying to read more bits than we have available"); } // Each character will require 2 bytes. Read the characters as 2-byte pairs diff --git a/lib/Qrcode/Decoder/Version.php b/lib/Qrcode/Decoder/Version.php index 5a6e0ca..536d23d 100644 --- a/lib/Qrcode/Decoder/Version.php +++ b/lib/Qrcode/Decoder/Version.php @@ -100,12 +100,12 @@ public function getECBlocksForLevel(ErrorCorrectionLevel $ecLevel) public static function getProvisionalVersionForDimension($dimension) { if ($dimension % 4 != 1) { - throw FormatException::getFormatInstance(); + throw new FormatException(); } try { return self::getVersionForNumber(($dimension - 17) / 4); } catch (\InvalidArgumentException) { - throw FormatException::getFormatInstance(); + throw new FormatException(); } } diff --git a/lib/Qrcode/Detector/FinderPatternFinder.php b/lib/Qrcode/Detector/FinderPatternFinder.php index c0fd99c..f6b3b35 100644 --- a/lib/Qrcode/Detector/FinderPatternFinder.php +++ b/lib/Qrcode/Detector/FinderPatternFinder.php @@ -58,6 +58,8 @@ final public function find(array|null $hints): \Zxing\Qrcode\Detector\FinderPatt $tryHarder = $hints != null && array_key_exists('TRY_HARDER', $hints) && $hints['TRY_HARDER']; $pureBarcode = $hints != null && array_key_exists('PURE_BARCODE', $hints) && $hints['PURE_BARCODE']; $nrOfRowsSkippable = $hints != null && array_key_exists('NR_ALLOW_SKIP_ROWS', $hints) ? $hints['NR_ALLOW_SKIP_ROWS'] : ($tryHarder ? 0 : null); + $allowedDeviation = $hints != null && array_key_exists('ALLOWED_DEVIATION', $hints) ? $hints['ALLOWED_DEVIATION'] : 0.05; + $maxVariance = $hints != null && array_key_exists('MAX_VARIANCE', $hints) ? $hints['MAX_VARIANCE'] : 0.5; $maxI = $this->image->getHeight(); $maxJ = $this->image->getWidth(); // We are looking for black/white/black/white/black modules in @@ -92,14 +94,14 @@ final public function find(array|null $hints): \Zxing\Qrcode\Detector\FinderPatt } else { // White pixel if (($currentState & 1) == 0) { // Counting black pixels if ($currentState == 4) { // A winner? - if (self::foundPatternCross($stateCount)) { // Yes + if (self::foundPatternCross($stateCount, $maxVariance)) { // Yes $confirmed = $this->handlePossibleCenter($stateCount, $i, $j, $pureBarcode); if ($confirmed) { // Start examining every other line. Checking each line turned out to be too // expensive and didn't improve performance. $iSkip = 3; if ($this->hasSkipped) { - $done = $this->haveMultiplyConfirmedCenters(); + $done = $this->haveMultiplyConfirmedCenters($allowedDeviation); } else { $rowSkip = $nrOfRowsSkippable === null ? $this->findRowSkip() : $nrOfRowsSkippable; if ($rowSkip > $stateCount[2]) { @@ -147,13 +149,13 @@ final public function find(array|null $hints): \Zxing\Qrcode\Detector\FinderPatt } } } - if (self::foundPatternCross($stateCount)) { + if (self::foundPatternCross($stateCount, $maxVariance)) { $confirmed = $this->handlePossibleCenter($stateCount, $i, $maxJ, $pureBarcode); if ($confirmed) { $iSkip = $stateCount[0]; if ($this->hasSkipped) { // Found a third one - $done = $this->haveMultiplyConfirmedCenters(); + $done = $this->haveMultiplyConfirmedCenters($allowedDeviation); } } } @@ -173,7 +175,7 @@ final public function find(array|null $hints): \Zxing\Qrcode\Detector\FinderPatt * * @psalm-param array<0|positive-int, int> $stateCount */ - protected static function foundPatternCross(array $stateCount): bool + protected static function foundPatternCross(array $stateCount, float $maxVariance = 0.5): bool { $totalModuleSize = 0; for ($i = 0; $i < 5; $i++) { @@ -187,7 +189,7 @@ protected static function foundPatternCross(array $stateCount): bool return false; } $moduleSize = $totalModuleSize / 7.0; - $maxVariance = $moduleSize / 2.0; + $maxVariance = $moduleSize * $maxVariance; // Allow less than 50% variance from 1-1-3-1-1 proportions return @@ -537,7 +539,7 @@ private function crossCheckDiagonal(int $startI, int $centerJ, $maxCount, int|fl /** * @return bool iff we have found at least 3 finder patterns that have been detected at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the candidates is "pretty similar" */ - private function haveMultiplyConfirmedCenters(): bool + private function haveMultiplyConfirmedCenters(?float $allowedDeviation = 0.05): bool { $confirmedCount = 0; $totalModuleSize = 0.0; @@ -561,7 +563,7 @@ private function haveMultiplyConfirmedCenters(): bool $totalDeviation += abs($pattern->getEstimatedModuleSize() - $average); } - return $totalDeviation <= 0.05 * $totalModuleSize; + return $totalDeviation <= $allowedDeviation * $totalModuleSize; } /** @@ -609,7 +611,7 @@ private function selectBestPatterns() $startSize = count($this->possibleCenters); if ($startSize < 3) { // Couldn't find enough finder patterns - throw new NotFoundException(); + throw new NotFoundException("Could not find 3 finder patterns ($startSize found)"); } // Filter outlier possibilities whose module size is too different diff --git a/tests/QrReaderTest.php b/tests/QrReaderTest.php index c893ed7..68dd7b7 100644 --- a/tests/QrReaderTest.php +++ b/tests/QrReaderTest.php @@ -11,7 +11,7 @@ class QrReaderTest extends TestCase public function setUp(): void { error_reporting(E_ALL); - ini_set('memory_limit','2G'); + ini_set('memory_limit', '2G'); } public function testText1() @@ -54,4 +54,19 @@ public function testText3() $this->assertSame(null, $qrcode->getError()); $this->assertSame("https://www.gosuslugi.ru/covid-cert/verify/9770000014233333?lang=ru&ck=733a9d218d312fe134f1c2cc06e1a800", $qrcode->text()); } + + // TODO: fix this test + // public function testText4() + // { + // $image = __DIR__ . "/qrcodes/174419877-f6b5dae1-2251-4b67-95f1-5e1143e40fae.jpg"; + // $qrcode = new QrReader($image); + // $qrcode->decode([ + // 'TRY_HARDER' => true, + // 'NR_ALLOW_SKIP_ROWS' => 0, + // // 'ALLOWED_DEVIATION' => 0.1, + // // 'MAX_VARIANCE' => 0.7 + // ]); + // $this->assertSame(null, $qrcode->getError()); + // $this->assertSame("some text", $qrcode->text()); + // } } diff --git a/tests/qrcodes/174419877-f6b5dae1-2251-4b67-95f1-5e1143e40fae.jpg b/tests/qrcodes/174419877-f6b5dae1-2251-4b67-95f1-5e1143e40fae.jpg new file mode 100644 index 0000000..17dceae Binary files /dev/null and b/tests/qrcodes/174419877-f6b5dae1-2251-4b67-95f1-5e1143e40fae.jpg differ