Recently one of our readers asked about how to resize the image in Laravel. Image resizing helps you to resize the image and improve your page speed also. In this article, we will discuss how to resize the image with the intervention image library.
Installation:
In this step, we need to install the intervention library in Laravel. Before this make sure you have a composer installed in your system. Open the terminal in your project and go to the root directory and run this command.
Composer require intervention/image After installation add the service providers in your config/app
Open config/app file and add some lines in providers arrays
Intervention\Image\ImageServiceProvider::class
And add the façade to aliases array also
‘Image’=>Intervention\Image|Facades\Image::class
Image Resizing
Before resizing the image create the storage directory under the public folder where we can store our uploaded image and thumbnail.
Php artisan storage:link
Now Create the form and write some code in that
In the controller we need to write some code to resize the image and before that add library façade image at the top of the controller.
namespace App\Http\Controllers; use Illuminate\Http\Request; use Image; class ImageController extends Controller { }
Now create our method store in our controller
public function store(Request $request) { if($request->hasFile('profile_image')) { //get filename with extension $filenamewithextension = $request->file('profile_image')->getClientOriginalName(); //get filename without extension $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME); //get file extension $extension = $request->file('profile_image')->getClientOriginalExtension(); //filename to store $filenametostore = $filename.'_'.time().'.'.$extension; //Upload File $request->file('profile_image')->storeAs('public/profile_images', $filenametostore); $request->file('profile_image')->storeAs('public/profile_images/thumbnail', $filenametostore); //Resize image here $thumbnailpath = public_path('storage/profile_images/thumbnail/'.$filenametostore); $img = Image::make($thumbnailpath)->resize(400, 150, function($constraint) { $constraint->aspectRatio(); }); $img->save($thumbnailpath); return redirect('images')->with('success', "Image uploaded successfully with resizing."); } }
You can change the resize values which we pass in resize() and it will resize the image and save to the database.
Conclusion:
In web development image resize is a required feature for use image as per the size of the web page container. By Image resize it will help us to improve our loading of web page speed. If you have any doubt in this article feel free to share your views on this. We want to hear from you.