|
8 | 8 |
|
9 | 9 | namespace le0daniel\Laravel\ImageEngine\Image;
|
10 | 10 |
|
| 11 | +use Illuminate\Support\Str; |
11 | 12 | use Intervention\Image\Constraint;
|
12 | 13 | use Intervention\Image\ImageManager;
|
13 | 14 | use le0daniel\Laravel\ImageEngine\Utility\Directories;
|
|
17 | 18 |
|
18 | 19 | final class ImageEngine
|
19 | 20 | {
|
| 21 | + private const IMAGE_RESIZE_DIMENSIONS_TO_FIT = 3000; |
| 22 | + |
20 | 23 | private array $sizes;
|
21 | 24 | private array $filters = [];
|
22 | 25 | private string $secret;
|
| 26 | + private string $tmpPath; |
23 | 27 | private ImageManager $imageManager;
|
24 | 28 |
|
25 | 29 | public function __construct(ImageManager $imageManager)
|
26 | 30 | {
|
27 | 31 | $this->imageManager = $imageManager;
|
28 | 32 | $this->sizes = config('image-engine.sizes');
|
29 | 33 | $this->secret = config('image-engine.key');
|
| 34 | + $this->tmpPath = rtrim(config('image-engine.tmp_directory'), '/'); |
30 | 35 | }
|
31 | 36 |
|
32 | 37 | private function getBasePath(ImageRepresentation $imageRepresentation, bool $forceConfidential): string
|
@@ -93,6 +98,12 @@ private function getAbsoluteRenderPath(
|
93 | 98 | return "{$basePath}/{$folder}/{$path}.{$extension}";
|
94 | 99 | }
|
95 | 100 |
|
| 101 | + private function getTmpPath(string $extension) |
| 102 | + { |
| 103 | + $randomName = Str::random(20); |
| 104 | + return "{$this->tmpPath}/{$randomName}.{$extension}"; |
| 105 | + } |
| 106 | + |
96 | 107 | public function serializeImage(ImageRepresentation $imageRepresentation): array
|
97 | 108 | {
|
98 | 109 | $signature = Signatures::sign($this->secret, $imageRepresentation->serialize());
|
@@ -169,4 +180,37 @@ static function (Constraint $constraint) {
|
169 | 180 | return $absoluteRenderPath;
|
170 | 181 | }
|
171 | 182 |
|
| 183 | + public function convertUploadedImage( |
| 184 | + string $absoluteImagePath, |
| 185 | + string $extension, |
| 186 | + \Closure $callback, |
| 187 | + int $imageDimensions = self::IMAGE_RESIZE_DIMENSIONS_TO_FIT |
| 188 | + ): void { |
| 189 | + Images::verifyImageExtension($extension); |
| 190 | + try { |
| 191 | + $tmpFileName = $this->getTmpPath($extension); |
| 192 | + |
| 193 | + $image = $this->imageManager->make($absoluteImagePath); |
| 194 | + $image->resize( |
| 195 | + $imageDimensions, |
| 196 | + $imageDimensions, |
| 197 | + static function ($constraint) { |
| 198 | + $constraint->aspectRatio(); |
| 199 | + $constraint->upsize(); |
| 200 | + } |
| 201 | + ); |
| 202 | + $image->save($tmpFileName); |
| 203 | + unset($image); |
| 204 | + |
| 205 | + $callback($tmpFileName); |
| 206 | + } catch (\Exception $exception) { |
| 207 | + if (file_exists($tmpFileName)) { |
| 208 | + unlink($tmpFileName); |
| 209 | + } |
| 210 | + throw $exception; |
| 211 | + } |
| 212 | + |
| 213 | + unlink($tmpFileName); |
| 214 | + } |
| 215 | + |
172 | 216 | }
|
0 commit comments