LabelImageData.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. declare(strict_types=1);
  3. namespace Endroid\QrCode\ImageData;
  4. use Endroid\QrCode\Label\LabelInterface;
  5. class LabelImageData
  6. {
  7. private int $width;
  8. private int $height;
  9. private function __construct(int $width, int $height)
  10. {
  11. $this->width = $width;
  12. $this->height = $height;
  13. }
  14. public static function createForLabel(LabelInterface $label): self
  15. {
  16. if (false !== strpos($label->getText(), "\n")) {
  17. throw new \Exception('Label does not support line breaks');
  18. }
  19. if (!function_exists('imagettfbbox')) {
  20. throw new \Exception('Function "imagettfbbox" does not exist: check your FreeType installation');
  21. }
  22. $labelBox = imagettfbbox($label->getFont()->getSize(), 0, $label->getFont()->getPath(), $label->getText());
  23. if (!is_array($labelBox)) {
  24. throw new \Exception('Unable to generate label image box: check your FreeType installation');
  25. }
  26. return new self(
  27. intval($labelBox[2] - $labelBox[0]),
  28. intval($labelBox[0] - $labelBox[7])
  29. );
  30. }
  31. public function getWidth(): int
  32. {
  33. return $this->width;
  34. }
  35. public function getHeight(): int
  36. {
  37. return $this->height;
  38. }
  39. }