|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * SPDX-License-Identifier: MIT |
| 5 | + * Copyright (c) 2017-2018 Tobias Reich |
| 6 | + * Copyright (c) 2018-2026 LycheeOrg. |
| 7 | + */ |
| 8 | + |
| 9 | +namespace App\Actions\Photo\Convert; |
| 10 | + |
| 11 | +use App\Contracts\PhotoCreate\PhotoConverter; |
| 12 | +use App\Exceptions\CannotConvertMediaFileException; |
| 13 | +use App\Image\Files\NativeLocalFile; |
| 14 | +use App\Image\Files\TemporaryJobFile; |
| 15 | +use App\Repositories\ConfigManager; |
| 16 | + |
| 17 | +class HeifToJpeg implements PhotoConverter |
| 18 | +{ |
| 19 | + public function __construct( |
| 20 | + private ConfigManager $config_manager, |
| 21 | + ) { |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * @throws \Exception |
| 26 | + */ |
| 27 | + public function handle(NativeLocalFile $tmp_file): TemporaryJobFile |
| 28 | + { |
| 29 | + if ($this->config_manager->hasImagick() === false) { |
| 30 | + throw new CannotConvertMediaFileException('Imagick is not available.'); |
| 31 | + } |
| 32 | + |
| 33 | + $path = $tmp_file->getRealPath(); |
| 34 | + $pathinfo = pathinfo($path); |
| 35 | + $file_name = $pathinfo['filename']; |
| 36 | + $new_path = $pathinfo['dirname'] . '/' . $file_name . '.jpg'; |
| 37 | + |
| 38 | + // Convert to Jpeg |
| 39 | + try { |
| 40 | + $imagick_converted = new \Imagick($path); |
| 41 | + |
| 42 | + if ($imagick_converted->getNumberImages() > 1) { |
| 43 | + $imagick_converted->setIteratorIndex(0); |
| 44 | + } |
| 45 | + |
| 46 | + $imagick_converted->setImageFormat('jpeg'); |
| 47 | + $imagick_converted->setImageCompression(\Imagick::COMPRESSION_JPEG); |
| 48 | + $imagick_converted->setImageCompressionQuality(92); |
| 49 | + |
| 50 | + $imagick_converted->autoOrient(); |
| 51 | + $imagick_converted->writeImage($new_path); |
| 52 | + } catch (\ImagickException $e) { |
| 53 | + throw new CannotConvertMediaFileException('Failed to convert HEIC/HEIF to JPEG.', $e); |
| 54 | + } |
| 55 | + |
| 56 | + // Delete old file |
| 57 | + $tmp_file->delete(); |
| 58 | + |
| 59 | + return new TemporaryJobFile($new_path); |
| 60 | + } |
| 61 | +} |
0 commit comments