Passed
Push — main ( 0a0d87...5e9cf0 )
by smiley
02:11
created

GDLuminanceSource::fromFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Class GDLuminanceSource
4
 *
5
 * @created      17.01.2021
6
 * @author       ZXing Authors
7
 * @author       Smiley <[email protected]>
8
 * @copyright    2021 Smiley
9
 * @license      Apache-2.0
10
 *
11
 * @noinspection PhpComposerExtensionStubsInspection
12
 */
13
14
namespace chillerlan\QRCode\Decoder;
15
16
use InvalidArgumentException;
17
use function file_get_contents, get_resource_type, imagecolorat, imagecolorsforindex,
18
	imagecreatefromstring, imagesx, imagesy, is_resource;
19
use const PHP_MAJOR_VERSION;
20
21
/**
22
 * This class is used to help decode images from files which arrive as GD Resource
23
 * It does not support rotation.
24
 */
25
final class GDLuminanceSource extends LuminanceSourceAbstract{
26
27
	/**
28
	 * @var resource|\GdImage
29
	 */
30
	private $gdImage;
31
32
	/**
33
	 * GDLuminanceSource constructor.
34
	 *
35
	 * @param resource|\GdImage $gdImage
36
	 *
37
	 * @throws \InvalidArgumentException
38
	 */
39
	public function __construct($gdImage){
40
41
		/** @noinspection PhpFullyQualifiedNameUsageInspection */
42
		if(
43
			(PHP_MAJOR_VERSION >= 8 && !$gdImage instanceof \GdImage)
44
			|| (!is_resource($gdImage) || get_resource_type($gdImage) !== 'gd')
45
		){
46
			throw new InvalidArgumentException('Invalid GD image source.');
47
		}
48
49
		parent::__construct(imagesx($gdImage), imagesy($gdImage));
50
51
		$this->gdImage = $gdImage;
52
53
		$this->setLuminancePixels();
54
	}
55
56
	/**
57
	 *
58
	 */
59
	private function setLuminancePixels():void{
60
		for($j = 0; $j < $this->height; $j++){
61
			for($i = 0; $i < $this->width; $i++){
62
				$argb  = imagecolorat($this->gdImage, $i, $j);
63
				$pixel = imagecolorsforindex($this->gdImage, $argb);
64
65
				$this->setLuminancePixel($pixel['red'], $pixel['green'], $pixel['blue']);
66
			}
67
		}
68
	}
69
70
	/** @inheritDoc */
71
	public static function fromFile(string $path):self{
72
		$path = self::checkFile($path);
73
74
		return new self(imagecreatefromstring(file_get_contents($path)));
75
	}
76
77
	/** @inheritDoc */
78
	public static function fromBlob(string $blob):self{
79
		return new self(imagecreatefromstring($blob));
80
	}
81
82
}
83