Tag Archives: imagemagic

Resize image in Laravel

To re size image in laravel we will use a library called Intervention.

Intervention Image is an open source PHP image handling and manipulation library. It provides an easier and expressive way to create, edit, and compose images and supports currently the two most common image processing libraries GD Library and Imagick. ( from their website)

So lets start with installation, the easiest way to install intervention is through composer. So run the following command in your terminal inside your application folder

composer require intervention/image

If it asks for specify version to be installed, add current stable version for this I will enter  2.1.2 (which is latest version at the time of writing this post) .

After you have installed Intervention Image, open your Laravel config file config/app.php and add the following lines.

In the $providers array add the service providers for this package.

‘Intervention\Image\ImageServiceProvider’

Add the facade of this package to the $aliases array.

‘Image’ => ‘Intervention\Image\Facades\Image’

Now the Image Class will be auto-loaded by Laravel.

Now we are done with the installation part, lets create a route to test our image re sizing.

// usage inside a laravel route

Route::get(‘/’, function() {

$img = Image::make(‘foo.jpg’)->resize(300, 200);

return $img->response(‘jpg’);

});

This will resize the provided image into 300 * 200 jpeg image. There some other options also, lets see them.

// To resize only the width of the image
$img->resize(300, null);

// To resize only the height of the image

$img->resize(null, 200);

// To resize the image to a width of 300 and constrain aspect ratio (auto height)
$img->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});

// To resize the image to a height of 200 and constrain aspect ratio (auto width)
$img->resize(null, 200, function ($constraint) {
$constraint->aspectRatio();
});

Besides image resize, intervention provides whole lot of functions to perform image manipulation. No matter if you want to create image thumbnails, watermarks or format large image files Intervention Image helps you to manage every task in an easy way with as little lines of code as possible.