I have this function to upload images via api in Laravel:
private function handleImage($image) { $exploded = explode(',', $image); $decoded = base64_decode($exploded[1]); if (Str::contains($exploded[0], 'jpeg')) { $extension = 'jpg'; } else { $extension = 'png'; } $fileName = Str::random() . '.' . $extension; $path = public_path() . '/images/products/' . $fileName; $file = file_put_contents($path, $decoded); $image = '/images/products/' . $fileName; return $image; }
How do I resize an image to a maximum side length of 500 pixels before uploading?
You can try using the Intervention Image package in Laravel to resize before uploading.
Install software package:
Composer Needs Intervention/Image
Add the following code at the beginning of the file to import the required classes:
Use Intervention\Image\ImageManagerStatic as image;
Use Illuminate\Support\Str;
Modify thehandleImagemethod as follows:
https://github.com/Intervention/image
Hope it helps you