QRGdImage.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. /**
  3. * Class QRGdImage
  4. *
  5. * @created 05.12.2015
  6. * @author Smiley <smiley@chillerlan.net>
  7. * @copyright 2015 Smiley
  8. * @license MIT
  9. *
  10. * @noinspection PhpComposerExtensionStubsInspection
  11. */
  12. declare(strict_types=1);
  13. namespace chillerlan\QRCode\Output;
  14. use chillerlan\QRCode\QROptions;
  15. use chillerlan\QRCode\Data\QRMatrix;
  16. use chillerlan\Settings\SettingsContainerInterface;
  17. use GdImage;
  18. use function extension_loaded, imagecolorallocate, imagecolortransparent,
  19. imagecreatetruecolor, imagedestroy, imagefilledellipse, imagefilledrectangle,
  20. imagescale, imagetypes, intdiv, intval, max, min, ob_end_clean, ob_get_contents, ob_start,
  21. sprintf;
  22. use const IMG_AVIF, IMG_BMP, IMG_GIF, IMG_JPG, IMG_PNG, IMG_WEBP;
  23. /**
  24. * Converts the matrix into GD images, raw or base64 output (requires ext-gd)
  25. *
  26. * @see https://php.net/manual/book.image.php
  27. * @see https://github.com/chillerlan/php-qrcode/issues/223
  28. */
  29. abstract class QRGdImage extends QROutputAbstract{
  30. use RGBArrayModuleValueTrait;
  31. /**
  32. * The GD image resource
  33. *
  34. * @see imagecreatetruecolor()
  35. */
  36. protected GdImage $image;
  37. /**
  38. * The allocated background color
  39. *
  40. * @see \imagecolorallocate()
  41. */
  42. protected int $background;
  43. /**
  44. * Whether we're running in upscale mode (scale < 20)
  45. *
  46. * @see \chillerlan\QRCode\QROptions::$drawCircularModules
  47. */
  48. protected bool $upscaled = false;
  49. /**
  50. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  51. * @noinspection PhpMissingParentConstructorInspection
  52. */
  53. public function __construct(SettingsContainerInterface|QROptions $options, QRMatrix $matrix){
  54. $this->options = $options;
  55. $this->matrix = $matrix;
  56. $this->checkGD();
  57. if($this->options->invertMatrix){
  58. $this->matrix->invert();
  59. }
  60. $this->copyVars();
  61. $this->setMatrixDimensions();
  62. }
  63. /**
  64. * Checks whether GD is installed and if the given mode is supported
  65. *
  66. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  67. * @codeCoverageIgnore
  68. */
  69. protected function checkGD():void{
  70. if(!extension_loaded('gd')){
  71. throw new QRCodeOutputException('ext-gd not loaded');
  72. }
  73. $modes = [
  74. QRGdImageAVIF::class => IMG_AVIF,
  75. QRGdImageBMP::class => IMG_BMP,
  76. QRGdImageGIF::class => IMG_GIF,
  77. QRGdImageJPEG::class => IMG_JPG,
  78. QRGdImagePNG::class => IMG_PNG,
  79. QRGdImageWEBP::class => IMG_WEBP,
  80. ];
  81. // likely using custom output/manual invocation
  82. if(!isset($modes[$this->options->outputInterface])){
  83. return;
  84. }
  85. $mode = $modes[$this->options->outputInterface];
  86. if((imagetypes() & $mode) !== $mode){
  87. throw new QRCodeOutputException(sprintf('output mode "%s" not supported', $this->options->outputInterface));
  88. }
  89. }
  90. /**
  91. * @inheritDoc
  92. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  93. */
  94. protected function prepareModuleValue(mixed $value):int{
  95. $values = [];
  96. foreach(array_values($value) as $i => $val){
  97. if($i > 2){
  98. break;
  99. }
  100. $values[] = max(0, min(255, intval($val)));
  101. }
  102. /** @phan-suppress-next-line PhanParamTooFewInternalUnpack */
  103. $color = imagecolorallocate($this->image, ...$values);
  104. if($color === false){
  105. throw new QRCodeOutputException('could not set color: imagecolorallocate() error');
  106. }
  107. return $color;
  108. }
  109. protected function getDefaultModuleValue(bool $isDark):int{
  110. return $this->prepareModuleValue(($isDark) ? [0, 0, 0] : [255, 255, 255]);
  111. }
  112. /**
  113. * @inheritDoc
  114. *
  115. * @throws \ErrorException|\chillerlan\QRCode\Output\QRCodeOutputException
  116. */
  117. public function dump(string|null $file = null):string|GdImage{
  118. $this->image = $this->createImage();
  119. // set module values after image creation because we need the GdImage instance
  120. $this->setModuleValues();
  121. $this->setBgColor();
  122. if(imagefilledrectangle($this->image, 0, 0, $this->length, $this->length, $this->background) === false){
  123. throw new QRCodeOutputException('imagefilledrectangle() error');
  124. }
  125. $this->drawImage();
  126. if($this->upscaled){
  127. // scale down to the expected size
  128. $scaled = imagescale($this->image, ($this->length / 10), ($this->length / 10));
  129. if($scaled === false){
  130. throw new QRCodeOutputException('imagescale() error');
  131. }
  132. $this->image = $scaled;
  133. $this->upscaled = false;
  134. // Reset scaled and length values after rescaling image to prevent issues with subclasses that use the output from dump()
  135. $this->setMatrixDimensions();
  136. }
  137. // set transparency after scaling, otherwise it would be undone
  138. // @see https://www.php.net/manual/en/function.imagecolortransparent.php#77099
  139. $this->setTransparencyColor();
  140. if($this->options->returnResource){
  141. return $this->image;
  142. }
  143. $imageData = $this->dumpImage();
  144. $this->saveToFile($imageData, $file);
  145. if($this->options->outputBase64){
  146. $imageData = $this->toBase64DataURI($imageData);
  147. }
  148. return $imageData;
  149. }
  150. /**
  151. * Creates a new GdImage resource and scales it if necessary
  152. *
  153. * we're scaling the image up in order to draw crisp round circles, otherwise they appear square-y on small scales
  154. *
  155. * @see https://github.com/chillerlan/php-qrcode/issues/23
  156. *
  157. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  158. */
  159. protected function createImage():GdImage{
  160. if($this->drawCircularModules && $this->options->gdImageUseUpscale && $this->options->scale < 20){
  161. // increase the initial image size by 10
  162. $this->length *= 10;
  163. $this->scale *= 10;
  164. $this->upscaled = true;
  165. }
  166. $im = imagecreatetruecolor($this->length, $this->length);
  167. if($im === false){
  168. throw new QRCodeOutputException('imagecreatetruecolor() error');
  169. }
  170. return $im;
  171. }
  172. /**
  173. * Sets the background color
  174. */
  175. protected function setBgColor():void{
  176. if(isset($this->background)){
  177. return;
  178. }
  179. if($this::moduleValueIsValid($this->options->bgColor)){
  180. $this->background = $this->prepareModuleValue($this->options->bgColor);
  181. return;
  182. }
  183. $this->background = $this->prepareModuleValue([255, 255, 255]);
  184. }
  185. /**
  186. * Sets the transparency color, returns the identifier of the new transparent color
  187. */
  188. protected function setTransparencyColor():int{
  189. if(!$this->options->imageTransparent){
  190. return -1;
  191. }
  192. $transparencyColor = $this->background;
  193. if($this::moduleValueIsValid($this->options->transparencyColor)){
  194. $transparencyColor = $this->prepareModuleValue($this->options->transparencyColor);
  195. }
  196. return imagecolortransparent($this->image, $transparencyColor);
  197. }
  198. /**
  199. * Returns the image quality value for the current GdImage output child class (defaults to -1 ... 100)
  200. */
  201. protected function getQuality():int{
  202. return max(-1, min(100, $this->options->quality));
  203. }
  204. /**
  205. * Draws the QR image
  206. */
  207. protected function drawImage():void{
  208. foreach($this->matrix->getMatrix() as $y => $row){
  209. foreach($row as $x => $M_TYPE){
  210. $this->module($x, $y, $M_TYPE);
  211. }
  212. }
  213. }
  214. /**
  215. * Creates a single QR pixel with the given settings
  216. */
  217. protected function module(int $x, int $y, int $M_TYPE):void{
  218. if(!$this->drawLightModules && !$this->matrix->isDark($M_TYPE)){
  219. return;
  220. }
  221. $color = $this->getModuleValue($M_TYPE);
  222. if($this->drawCircularModules && !$this->matrix->checkTypeIn($x, $y, $this->keepAsSquare)){
  223. imagefilledellipse(
  224. $this->image,
  225. (($x * $this->scale) + intdiv($this->scale, 2)),
  226. (($y * $this->scale) + intdiv($this->scale, 2)),
  227. (int)($this->circleDiameter * $this->scale),
  228. (int)($this->circleDiameter * $this->scale),
  229. $color,
  230. );
  231. return;
  232. }
  233. imagefilledrectangle(
  234. $this->image,
  235. ($x * $this->scale),
  236. ($y * $this->scale),
  237. (($x + 1) * $this->scale),
  238. (($y + 1) * $this->scale),
  239. $color,
  240. );
  241. }
  242. /**
  243. * Renders the image with the gdimage function for the desired output
  244. *
  245. * @see https://github.com/chillerlan/php-qrcode/issues/223
  246. */
  247. abstract protected function renderImage():void;
  248. /**
  249. * Creates the final image by calling the desired GD output function
  250. *
  251. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  252. */
  253. protected function dumpImage():string{
  254. ob_start();
  255. $this->renderImage();
  256. $imageData = ob_get_contents();
  257. if($imageData === false){
  258. throw new QRCodeOutputException('ob_get_contents() error');
  259. }
  260. imagedestroy($this->image);
  261. ob_end_clean();
  262. return $imageData;
  263. }
  264. }