Image handling with intervention/image

Want to process images ? This tip gives you some practical examples on how to do that

2 minutes

Image handling with intervention/image

Very nice and simple api

Image intervention Image intervention provides us with a fluent and simple api. It becomes very easy to transform images in several ways. The most popular use case for images manipulation is resizing. I'll give you a few examples on how to handle it.

The source code of this tip can be tested via the Lloadout tutorials GitHub repo. If you better like watching video you can watch my YouTube video on image intervention.

Loading an image

The make command provides you with a simple function to transform images to image objects. You can load urls, image streams, paths.

This example loads an image from an external resource and returns it to the browser as a jpg.

$img = Image::make('');
return $img->response('jpg');

If you want to rotate your image you can call rotate on the image with the number of degrees you want to rotate the image on.


Resizing an image

If you want to resize an image then you call the resize method with the width and height arguments, this will force the image to be returned in the provide dimensions ( not keeping the aspect ratio )

return $img->resize(300,400)->response('jpg');

resizing keeping aspect ratio

Giving your image an absolute with and height is often not a very good idea, your aspect ratio will get lost and images will look very weird. So its possible to keep the aspectratio of the image.

return $img->resize(200, null, function ($constraint) {

Prevent possible upsizing

Another side effect of image resizing is possible upsizing, images get blurry by upsizing so it's better to prevent it. This can easily be done.

return $img->resize(null, 1000, function ($constraint) {

Saving a processed image

If you want to handle a file and save it somewhere you can store it on your file system , eventually using Laravel disks if you want to.

return $img->save(storage_path()."/lesson1/lesson1.jpg",80,'jpg');

Colorizing images

Sites using a lot of images in different colors can look overwhelming , that's why it might be a good idea to transform the images to be grayscale.

return $img->greyscale()->response('jpg');

Maybe you want to give all your images a specific color

return $img->colorize(-100, 0, 100)->response('jpg');

Writing text on an image

In some cases you might want to add text to your images. A common use case for text on an image is a watermark stamp.

return $img->text($_GET['text'] ?? 'LESSON 1', 20, 40, function($font) {

this article has been read 63 times