Skip to content

Commit

Permalink
Merge pull request #132 from GenieTim/master
Browse files Browse the repository at this point in the history
Next iteration of improvements
  • Loading branch information
khanamiryan authored Oct 20, 2022
2 parents 69c49a5 + e236a0e commit b331b0e
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 41 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@
/vendor
.idea/
.phpunit.result.cache

tests/qrcodes/private_test.png
tests/qrcodes/private_test2.png
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.<br />This is first and only QR code reader that works without extensions.<br />
Ported from [ZXing library](https://github.com/zxing/zxing)

Expand Down
4 changes: 2 additions & 2 deletions lib/Common/HybridBinarizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
Expand Down Expand Up @@ -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);
}
}
Expand Down
7 changes: 5 additions & 2 deletions lib/Common/PerspectiveTransform.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/IMagickLuminanceSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 4 additions & 4 deletions lib/Qrcode/Decoder/BitMatrixParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -156,7 +156,7 @@ public function readFormatInformation()
if ($parsedFormatInfo != null) {
return $parsedFormatInfo;
}
throw FormatException::getFormatInstance();
throw new FormatException();
}

/**
Expand Down Expand Up @@ -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");
}

/**
Expand Down
41 changes: 21 additions & 20 deletions lib/Qrcode/Decoder/DecodedBitStreamParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -112,15 +112,15 @@ 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");
}
}
}
}
} 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(
Expand Down Expand Up @@ -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.");
}

/**
Expand All @@ -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
Expand Down Expand Up @@ -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));
}
Expand All @@ -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(
Expand All @@ -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));
Expand All @@ -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));
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions lib/Qrcode/Decoder/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

Expand Down
20 changes: 11 additions & 9 deletions lib/Qrcode/Detector/FinderPatternFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]) {
Expand Down Expand Up @@ -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);
}
}
}
Expand All @@ -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++) {
Expand All @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -561,7 +563,7 @@ private function haveMultiplyConfirmedCenters(): bool
$totalDeviation += abs($pattern->getEstimatedModuleSize() - $average);
}

return $totalDeviation <= 0.05 * $totalModuleSize;
return $totalDeviation <= $allowedDeviation * $totalModuleSize;
}

/**
Expand Down Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion tests/QrReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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());
// }
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit b331b0e

Please sign in to comment.