Resizing uploaded file and saving with the same name in the same location

59 Views Asked by At

I try to save an image and resize with Intervention. Filesystem.php has default settings for Laravel 10.

I can successfully save under storage/app/public/image:

$file->storeAs('public/image/', $uniqueFileName);

Than I try to resize and save with same name.

$manager = new ImageManager();
$resizedImage = $manager->make(storage_path('app/public/image/' . $uniqueFileName))->resize(100, 100);
Storage::disk('public')->put(storage_path('public/image/' . $uniqueFileName), $resizedImage);

The problem is, last line creates such a folder and tries to save under this location:

/storage/app/public/Users/tolga/Desktop/project-path/storage/image

Resized images under this location are empty files actually.

2

There are 2 best solutions below

0
tolga On BEST ANSWER

As Aro mentioned, I removed storage_path from Storage:put method, but than I realized that I actually don't need this line, with Intervention.

I first added as alias:

'aliases' => Facade::defaultAliases()->merge([
    'Image' => Intervention\Image\ImageManagerStatic::class,

Than, as a one liner code:

use Image;

...

Image::make(storage_path('app/public/image/' . $uniqueFileName))->fit(200, 200)->save();

This resizes as a square, even the image file is not square and than saves with the same name.

1
Arayik G. On

You shouldn't generate a path with storage_path if you are using Storage facade, because storage_path will generate an absolute path, but Storage facade with disk local or public already knows the path to storage. So just write like this

  Storage::disk('public')->put('relative path in storage', $file);