dev-think-one /
laravel-thinkqr
| 1 | <?php |
||
| 2 | |||
| 3 | namespace ThinkQR\Image; |
||
| 4 | |||
| 5 | use Intervention\Image\ImageManagerStatic; |
||
| 6 | use ThinkQR\QRCode; |
||
| 7 | |||
| 8 | class QrCodeImageForPdf |
||
| 9 | { |
||
| 10 | protected string $tmpFileName = ''; |
||
| 11 | |||
| 12 | 1 | public function __construct(string $content, array $options = []) |
|
| 13 | { |
||
| 14 | 1 | $this->tmpFileName = $this->generateTemporalFileName('png'); |
|
| 15 | 1 | ( new QRCode($content, $options) )->writePngFile($this->tmpFileName); |
|
| 16 | 1 | static::convertImageTo8bit($this->tmpFileName); |
|
| 17 | } |
||
| 18 | |||
| 19 | 1 | public static function make(...$arguments): static |
|
| 20 | { |
||
| 21 | 1 | return new static(...$arguments); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 22 | } |
||
| 23 | |||
| 24 | 1 | public function filePath(): string |
|
| 25 | { |
||
| 26 | 1 | return $this->tmpFileName; |
|
| 27 | } |
||
| 28 | |||
| 29 | /** |
||
| 30 | * Create temporal file name. |
||
| 31 | * |
||
| 32 | * @param string|null $ext |
||
| 33 | * |
||
| 34 | * @return string |
||
| 35 | * @throws \Exception |
||
| 36 | */ |
||
| 37 | 1 | protected function generateTemporalFileName(?string $ext = null): string |
|
| 38 | { |
||
| 39 | 1 | $name = tempnam(sys_get_temp_dir(), 'gen_pdf_image_qr'); |
|
| 40 | 1 | if ($ext) { |
|
| 41 | 1 | $name = "{$name}.{$ext}"; |
|
| 42 | } |
||
| 43 | 1 | if (!$name) { |
|
| 44 | throw new \Exception('Temporal file name can\'t be created.'); |
||
| 45 | } |
||
| 46 | |||
| 47 | 1 | return $name; |
|
| 48 | } |
||
| 49 | |||
| 50 | /** |
||
| 51 | * FPDF support only 8 bit colors - so we need convert image before insert |
||
| 52 | * @param string $path |
||
| 53 | */ |
||
| 54 | 1 | public static function convertImageTo8bit(string $path): void |
|
| 55 | { |
||
| 56 | 1 | $img = ImageManagerStatic::make($path); |
|
| 57 | 1 | $img->limitColors(255, '#ffffff'); |
|
| 58 | 1 | $img->save($path); |
|
| 59 | } |
||
| 60 | } |
||
| 61 |