diff --git a/src/Form/Fields/Formatters/UploadFormatter.php b/src/Form/Fields/Formatters/UploadFormatter.php index ec134d3a3..ff6456a79 100644 --- a/src/Form/Fields/Formatters/UploadFormatter.php +++ b/src/Form/Fields/Formatters/UploadFormatter.php @@ -6,6 +6,7 @@ use Code16\Sharp\Form\Fields\SharpFormUploadField; use Code16\Sharp\Utils\FileUtil; use Code16\Sharp\Utils\Uploads\SharpUploadManager; +use Illuminate\Filesystem\LocalFilesystemAdapter; use Illuminate\Support\Facades\Storage; class UploadFormatter extends SharpFieldFormatter implements FormatsAfterUpdate @@ -50,7 +51,7 @@ public function fromFront(SharpFormField $field, string $attribute, $value): ?ar 'filters' => $field->isImageTransformOriginal() ? null : $value['filters'] ?? null, - ]), function ($formatted) use ($field, $value) { + ]), function (&$formatted) use ($field, $value, $uploadedFieldRelativePath) { if ($field->storageDisk()) { app(SharpUploadManager::class)->queueHandleUploadedFile( uploadedFileName: $value['name'], @@ -63,6 +64,11 @@ public function fromFront(SharpFormField $field, string $attribute, $value): ?ar : null, ); } + + if ($dimensions = $this->getImageDimensions($uploadedFieldRelativePath, $formatted['mime_type'])) { + $formatted['width'] = $dimensions['width']; + $formatted['height'] = $dimensions['height']; + } }); } @@ -108,4 +114,27 @@ protected function normalizeFromFront(?array $value, ?array $formatted = null): 'filters' => $formatted['filters'] ?? $value['filters'] ?? null, ])->whereNotNull()->toArray(); } + + protected function getImageDimensions(string $tmpFilePath, string $mimeType): ?array + { + // image size only available if tmp is stored locally + if (! Storage::disk(sharp()->config()->get('uploads.tmp_disk')) instanceof LocalFilesystemAdapter) { + return null; + } + + if (! str_starts_with($mimeType, 'image/')) { + return null; + } + + $realPath = Storage::disk(sharp()->config()->get('uploads.tmp_disk'))->path($tmpFilePath); + + if ($size = @getimagesize($realPath)) { + return [ + 'width' => $size[0], + 'height' => $size[1], + ]; + } + + return null; + } } diff --git a/tests/Unit/Form/Fields/Formatters/UploadFormatterTest.php b/tests/Unit/Form/Fields/Formatters/UploadFormatterTest.php index e2bc59cac..c8fc0c282 100644 --- a/tests/Unit/Form/Fields/Formatters/UploadFormatterTest.php +++ b/tests/Unit/Form/Fields/Formatters/UploadFormatterTest.php @@ -127,7 +127,7 @@ $formatter = app(UploadFormatter::class); UploadedFile::fake() - ->image('image.jpg') + ->image('image.jpg', width: 10, height: 10) ->storeAs('/tmp', 'image.jpg', ['disk' => 'local']); $field = SharpFormUploadField::make('upload')->setStorageTemporary(); @@ -144,5 +144,7 @@ 'disk' => 'local', 'mime_type' => 'image/jpeg', 'size' => 695, + 'width' => 10, + 'height' => 10, ]); });