GDLuminanceSource.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * Class GDLuminanceSource
  4. *
  5. * @created 17.01.2021
  6. * @author ZXing Authors
  7. * @author Smiley <smiley@chillerlan.net>
  8. * @copyright 2021 Smiley
  9. * @license Apache-2.0
  10. *
  11. * @noinspection PhpComposerExtensionStubsInspection
  12. */
  13. namespace chillerlan\QRCode\Decoder;
  14. use InvalidArgumentException;
  15. use function get_resource_type, imagecolorat, imagecolorsforindex, imagesx, imagesy, is_resource;
  16. use const PHP_MAJOR_VERSION;
  17. /**
  18. * This class is used to help decode images from files which arrive as GD Resource
  19. * It does not support rotation.
  20. */
  21. final class GDLuminanceSource extends LuminanceSource{
  22. /**
  23. * @var resource|\GdImage
  24. */
  25. private $gdImage;
  26. /**
  27. * GDLuminanceSource constructor.
  28. *
  29. * @param resource|\GdImage $gdImage
  30. *
  31. * @throws \InvalidArgumentException
  32. */
  33. public function __construct($gdImage){
  34. /** @noinspection PhpFullyQualifiedNameUsageInspection */
  35. if(
  36. (PHP_MAJOR_VERSION >= 8 && !$gdImage instanceof \GdImage)
  37. || (PHP_MAJOR_VERSION < 8 && (!is_resource($gdImage) || get_resource_type($gdImage) !== 'gd'))
  38. ){
  39. throw new InvalidArgumentException('Invalid GD image source.');
  40. }
  41. parent::__construct(imagesx($gdImage), imagesy($gdImage));
  42. $this->gdImage = $gdImage;
  43. $this->setLuminancePixels();
  44. }
  45. /**
  46. *
  47. */
  48. private function setLuminancePixels():void{
  49. for($j = 0; $j < $this->height; $j++){
  50. for($i = 0; $i < $this->width; $i++){
  51. $argb = imagecolorat($this->gdImage, $i, $j);
  52. $pixel = imagecolorsforindex($this->gdImage, $argb);
  53. $this->setLuminancePixel($pixel['red'], $pixel['green'], $pixel['blue']);
  54. }
  55. }
  56. }
  57. }