zend-blog-3-backend
99 строк · 2.9 Кб
1<?php
2
3namespace App\Model\Resizer;4
5use App\Model\ResizerInterface;6use Imagick;7use ImagickException;8use Symfony\Component\Process\Exception\ProcessFailedException;9use Symfony\Component\Process\Process;10
11class AvifResizer implements ResizerInterface12{
13use DebugAnnotation;14
15/**16* @throws ImagickException
17*/
18public function resize(string $filePath, string $newFilePath, int $width, int $height)19{20$image = new Imagick($filePath);21$image->stripImage();22
23$image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1);24
25$image->setFormat('png');26$image->setImageFormat('png');27
28$image->setCompression(Imagick::COMPRESSION_ZIP);29$image->setImageCompression(Imagick::COMPRESSION_ZIP);30
31//$this->annotate($width, $height, $image);32
33$tmpfile = sys_get_temp_dir() . '/' . uniqid() . '.png';34$image->writeImage($tmpfile);35$image->clear();36
37/**38* TODO rework:
39*
40* User Deprecated: Passing a command as string when creating a "Symfony\Component\Process\Process" instance
41* is deprecated since Symfony 4.2, pass it as an array of its arguments instead, or use
42* the "Process::fromShellCommandline()" constructor if you need features provided by the shell.
43*/
44$process = new Process(45'/usr/bin/cavif --quality=75 --speed=1 --depth=8 --quiet -o ' . escapeshellarg($newFilePath) . ' ' . $tmpfile46);47$process->run();48unlink($tmpfile);49
50if (!$process->isSuccessful()) {51throw new ProcessFailedException($process);52}53}54
55/**56* @throws ImagickException
57*/
58public function convert(string $filePath, string $resourcePath): string59{60$pathInfo = pathinfo($filePath);61$newFilePath = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '.avif';62if (file_exists($resourcePath . '/' . $newFilePath)) {63return $newFilePath;64}65
66$image = new Imagick($resourcePath . '/' . $filePath);67$image->stripImage();68
69$image->setFormat('png');70$image->setImageFormat('png');71
72$image->setCompression(Imagick::COMPRESSION_ZIP);73$image->setImageCompression(Imagick::COMPRESSION_ZIP);74
75//$this->annotate(0, 0, $image);76
77$tmpfile = sys_get_temp_dir() . '/' . uniqid() . '.png';78$image->writeImage($tmpfile);79$image->clear();80
81$process = new Process(82'/usr/bin/cavif --quality=75 --speed=1 --depth=8 --quiet -o ' . escapeshellarg($resourcePath . '/' . $newFilePath)83. ' ' . $tmpfile84);85$process->run();86unlink($tmpfile);87
88if (!$process->isSuccessful()) {89throw new ProcessFailedException($process);90}91
92return $newFilePath;93}94
95protected function getFormat(): string96{97return 'avif';98}99}
100