Here are the steps on how to resize an image in Laravel:
Step 1: Install the Intervention Image package.
composer require intervention/image
Step 2: Register the Intervention Image service provider in your config/app.php
file.
'providers' => [
...
Intervention\Image\ImageServiceProvider::class,
...
],
Step 3: Create a new controller file and add the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Intervention\Image\ImageManagerStatic;
class ImageController extends Controller
{
public function resizeImage(Request $request)
{
$image = $request->file('image');
$img = ImageManagerStatic::make($image->path());
$img->resize(100, 100)->save();
return $img->response();
}
}
Step 4: Create a new route in your routes/web.php
file that points to the resizeImage()
method in your controller.
Route::post('/resize-image', 'ImageController@resizeImage');
Step 4: Test the route by uploading an image to the /resize-image
endpoint. The image will be resized to 100x100 pixels and the resized image will be returned in the response.
Here is an explanation of the code:
- The
ImageManagerStatic
class is used to create and manipulate images. - The
resize()
method is used to resize the image. - The
save()
method is used to save the resized image. - The
response()
method is used to return the resized image in the response.
I hope this helps. Thanks!
Discussion