PngWriter.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * (c) Jeroen van den Enden <info@endroid.nl>
  5. *
  6. * This source file is subject to the MIT license that is bundled
  7. * with this source code in the file LICENSE.
  8. */
  9. namespace Endroid\QrCode\Writer;
  10. use Endroid\QrCode\Exception\GenerateImageException;
  11. use Endroid\QrCode\Exception\MissingFunctionException;
  12. use Endroid\QrCode\Exception\MissingLogoHeightException;
  13. use Endroid\QrCode\Exception\ValidationException;
  14. use Endroid\QrCode\LabelAlignment;
  15. use Endroid\QrCode\QrCodeInterface;
  16. use Zxing\QrReader;
  17. class PngWriter extends AbstractWriter
  18. {
  19. public function writeString(QrCodeInterface $qrCode): string
  20. {
  21. if (!extension_loaded('gd')) {
  22. throw new GenerateImageException('Unable to generate image: check your GD installation');
  23. }
  24. $image = $this->createImage($qrCode->getData(), $qrCode);
  25. $logoPath = $qrCode->getLogoPath();
  26. if (null !== $logoPath) {
  27. $image = $this->addLogo($image, $logoPath, $qrCode->getLogoWidth(), $qrCode->getLogoHeight());
  28. }
  29. $label = $qrCode->getLabel();
  30. if (null !== $label) {
  31. $image = $this->addLabel($image, $label, $qrCode->getLabelFontPath(), $qrCode->getLabelFontSize(), $qrCode->getLabelAlignment(), $qrCode->getLabelMargin(), $qrCode->getForegroundColor(), $qrCode->getBackgroundColor());
  32. }
  33. $string = $this->imageToString($image);
  34. if (PHP_VERSION_ID < 80000) {
  35. imagedestroy($image);
  36. }
  37. if ($qrCode->getValidateResult()) {
  38. $reader = new QrReader($string, QrReader::SOURCE_TYPE_BLOB);
  39. if ($reader->text() !== $qrCode->getText()) {
  40. throw new ValidationException('Built-in validation reader read "'.$reader->text().'" instead of "'.$qrCode->getText().'".
  41. Adjust your parameters to increase readability or disable built-in validation.');
  42. }
  43. }
  44. return $string;
  45. }
  46. /**
  47. * @param array<mixed> $data
  48. *
  49. * @return mixed
  50. */
  51. private function createImage(array $data, QrCodeInterface $qrCode)
  52. {
  53. $baseSize = $qrCode->getRoundBlockSize() ? $data['block_size'] : 25;
  54. $baseImage = $this->createBaseImage($baseSize, $data, $qrCode);
  55. $interpolatedImage = $this->createInterpolatedImage($baseImage, $data, $qrCode);
  56. if (PHP_VERSION_ID < 80000) {
  57. imagedestroy($baseImage);
  58. }
  59. return $interpolatedImage;
  60. }
  61. /**
  62. * @param array<mixed> $data
  63. *
  64. * @return mixed
  65. */
  66. private function createBaseImage(int $baseSize, array $data, QrCodeInterface $qrCode)
  67. {
  68. $image = imagecreatetruecolor($data['block_count'] * $baseSize, $data['block_count'] * $baseSize);
  69. if (!$image) {
  70. throw new GenerateImageException('Unable to generate image: check your GD installation');
  71. }
  72. $foregroundColor = imagecolorallocatealpha($image, $qrCode->getForegroundColor()['r'], $qrCode->getForegroundColor()['g'], $qrCode->getForegroundColor()['b'], $qrCode->getForegroundColor()['a']);
  73. if (!is_int($foregroundColor)) {
  74. throw new GenerateImageException('Foreground color could not be allocated');
  75. }
  76. $backgroundColor = imagecolorallocatealpha($image, $qrCode->getBackgroundColor()['r'], $qrCode->getBackgroundColor()['g'], $qrCode->getBackgroundColor()['b'], $qrCode->getBackgroundColor()['a']);
  77. if (!is_int($backgroundColor)) {
  78. throw new GenerateImageException('Background color could not be allocated');
  79. }
  80. imagefill($image, 0, 0, $backgroundColor);
  81. foreach ($data['matrix'] as $row => $values) {
  82. foreach ($values as $column => $value) {
  83. if (1 === $value) {
  84. imagefilledrectangle($image, $column * $baseSize, $row * $baseSize, intval(($column + 1) * $baseSize), intval(($row + 1) * $baseSize), $foregroundColor);
  85. }
  86. }
  87. }
  88. return $image;
  89. }
  90. /**
  91. * @param mixed $baseImage
  92. * @param array<mixed> $data
  93. *
  94. * @return mixed
  95. */
  96. private function createInterpolatedImage($baseImage, array $data, QrCodeInterface $qrCode)
  97. {
  98. $image = imagecreatetruecolor($data['outer_width'], $data['outer_height']);
  99. if (!$image) {
  100. throw new GenerateImageException('Unable to generate image: check your GD installation');
  101. }
  102. $backgroundColor = imagecolorallocatealpha($image, $qrCode->getBackgroundColor()['r'], $qrCode->getBackgroundColor()['g'], $qrCode->getBackgroundColor()['b'], $qrCode->getBackgroundColor()['a']);
  103. if (!is_int($backgroundColor)) {
  104. throw new GenerateImageException('Background color could not be allocated');
  105. }
  106. imagefill($image, 0, 0, $backgroundColor);
  107. imagecopyresampled($image, $baseImage, (int) $data['margin_left'], (int) $data['margin_left'], 0, 0, (int) $data['inner_width'], (int) $data['inner_height'], imagesx($baseImage), imagesy($baseImage));
  108. if ($qrCode->getBackgroundColor()['a'] > 0) {
  109. imagesavealpha($image, true);
  110. }
  111. return $image;
  112. }
  113. /**
  114. * @param mixed $sourceImage
  115. *
  116. * @return mixed
  117. */
  118. private function addLogo($sourceImage, string $logoPath, int $logoWidth = null, int $logoHeight = null)
  119. {
  120. $mimeType = $this->getMimeType($logoPath);
  121. $logoImage = imagecreatefromstring(strval(file_get_contents($logoPath)));
  122. if ('image/svg+xml' === $mimeType && (null === $logoHeight || null === $logoWidth)) {
  123. throw new MissingLogoHeightException('SVG Logos require an explicit height set via setLogoSize($width, $height)');
  124. }
  125. if (!$logoImage) {
  126. throw new GenerateImageException('Unable to generate image: check your GD installation or logo path');
  127. }
  128. $logoSourceWidth = imagesx($logoImage);
  129. $logoSourceHeight = imagesy($logoImage);
  130. if (null === $logoWidth) {
  131. $logoWidth = $logoSourceWidth;
  132. }
  133. if (null === $logoHeight) {
  134. $aspectRatio = $logoWidth / $logoSourceWidth;
  135. $logoHeight = intval($logoSourceHeight * $aspectRatio);
  136. }
  137. $logoX = imagesx($sourceImage) / 2 - $logoWidth / 2;
  138. $logoY = imagesy($sourceImage) / 2 - $logoHeight / 2;
  139. imagecopyresampled($sourceImage, $logoImage, intval($logoX), intval($logoY), 0, 0, $logoWidth, $logoHeight, $logoSourceWidth, $logoSourceHeight);
  140. if (PHP_VERSION_ID < 80000) {
  141. imagedestroy($logoImage);
  142. }
  143. return $sourceImage;
  144. }
  145. /**
  146. * @param mixed $sourceImage
  147. * @param array<int> $labelMargin
  148. * @param array<int> $foregroundColor
  149. * @param array<int> $backgroundColor
  150. *
  151. * @return mixed
  152. */
  153. private function addLabel($sourceImage, string $label, string $labelFontPath, int $labelFontSize, string $labelAlignment, array $labelMargin, array $foregroundColor, array $backgroundColor)
  154. {
  155. if (!function_exists('imagettfbbox')) {
  156. throw new MissingFunctionException('Missing function "imagettfbbox", please make sure you installed the FreeType library');
  157. }
  158. $labelBox = imagettfbbox($labelFontSize, 0, $labelFontPath, $label);
  159. if (!$labelBox) {
  160. throw new GenerateImageException('Unable to add label: check your GD installation');
  161. }
  162. $labelBoxWidth = intval($labelBox[2] - $labelBox[0]);
  163. $labelBoxHeight = intval($labelBox[0] - $labelBox[7]);
  164. $sourceWidth = imagesx($sourceImage);
  165. $sourceHeight = imagesy($sourceImage);
  166. $targetWidth = $sourceWidth;
  167. $targetHeight = $sourceHeight + $labelBoxHeight + $labelMargin['t'] + $labelMargin['b'];
  168. // Create empty target image
  169. $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
  170. if (!$targetImage) {
  171. throw new GenerateImageException('Unable to generate image: check your GD installation');
  172. }
  173. $foregroundColor = imagecolorallocate($targetImage, $foregroundColor['r'], $foregroundColor['g'], $foregroundColor['b']);
  174. if (!is_int($foregroundColor)) {
  175. throw new GenerateImageException('Foreground color could not be allocated');
  176. }
  177. $backgroundColor = imagecolorallocate($targetImage, $backgroundColor['r'], $backgroundColor['g'], $backgroundColor['b']);
  178. if (!is_int($backgroundColor)) {
  179. throw new GenerateImageException('Background color could not be allocated');
  180. }
  181. imagefill($targetImage, 0, 0, $backgroundColor);
  182. // Copy source image to target image
  183. imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $sourceWidth, $sourceHeight, $sourceWidth, $sourceHeight);
  184. if (PHP_VERSION_ID < 80000) {
  185. imagedestroy($sourceImage);
  186. }
  187. switch ($labelAlignment) {
  188. case LabelAlignment::LEFT:
  189. $labelX = $labelMargin['l'];
  190. break;
  191. case LabelAlignment::RIGHT:
  192. $labelX = $targetWidth - $labelBoxWidth - $labelMargin['r'];
  193. break;
  194. default:
  195. $labelX = intval($targetWidth / 2 - $labelBoxWidth / 2);
  196. break;
  197. }
  198. $labelY = $targetHeight - $labelMargin['b'];
  199. imagettftext($targetImage, $labelFontSize, 0, $labelX, $labelY, $foregroundColor, $labelFontPath, $label);
  200. return $targetImage;
  201. }
  202. /**
  203. * @param mixed $image
  204. */
  205. private function imageToString($image): string
  206. {
  207. ob_start();
  208. imagepng($image);
  209. return (string) ob_get_clean();
  210. }
  211. public static function getContentType(): string
  212. {
  213. return 'image/png';
  214. }
  215. public static function getSupportedExtensions(): array
  216. {
  217. return ['png'];
  218. }
  219. public function getName(): string
  220. {
  221. return 'png';
  222. }
  223. }