zend-blog-3-backend
77 строк · 2.1 Кб
1<?php
2
3namespace App\Model\Resizer;
4
5use App\Model\ResizerInterface;
6use Imagick;
7use ImagickException;
8
9class WebpResizer implements ResizerInterface
10{
11use DebugAnnotation;
12
13/**
14* @throws ImagickException
15*/
16public function resize(string $filePath, string $newFilePath, int $width, int $height)
17{
18if (!Imagick::queryFormats('WEBP')) {
19throw new \RuntimeException('Webp format is not supported by Imagick installation.');
20}
21
22$image = new Imagick($filePath);
23$image->stripImage();
24
25$image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1);
26
27$image->setFormat($this->getFormat());
28$image->setImageFormat($this->getFormat());
29
30$image->setCompression(Imagick::COMPRESSION_JPEG);
31$image->setImageCompression(Imagick::COMPRESSION_JPEG);
32$image->setImageCompressionQuality(80);
33
34//$this->annotate($width, $height, $image);
35
36$image->writeImage($newFilePath);
37$image->clear();
38}
39
40/**
41* @throws ImagickException
42*/
43public function convert(string $filePath, string $resourcePath): string
44{
45if (!Imagick::queryFormats('WEBP')) {
46throw new \RuntimeException('Webp format is not supported by Imagick installation.');
47}
48
49$pathInfo = pathinfo($filePath);
50$newFilePath = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '.webp';
51if (file_exists($resourcePath . '/' . $newFilePath)) {
52return $newFilePath;
53}
54
55$image = new Imagick($resourcePath . '/' . $filePath);
56$image->stripImage();
57
58$image->setFormat($this->getFormat());
59$image->setImageFormat($this->getFormat());
60
61$image->setCompression(Imagick::COMPRESSION_JPEG);
62$image->setImageCompression(Imagick::COMPRESSION_JPEG);
63$image->setImageCompressionQuality(80);
64
65//$this->annotate(0, 0, $image);
66
67$image->writeImage($resourcePath . '/' . $newFilePath);
68$image->clear();
69
70return $newFilePath;
71}
72
73protected function getFormat(): string
74{
75return 'webp';
76}
77}
78