Thumbnails in Laravel

Currently I received a requirement to create a thumbnail of images, the idea was to use the uri of the file, the relative path of the image from the public folder, and create inside of a thumbs directory the equivalent of the image.

Looking for tools to create thumbnails I found Intervention, this is a library that runs over GD or ImageMagic and allow us to resize, change width, hight, canvas size or even put some water marks into the images.

Let’s see what I did.

Installation

To install the library just use composer, in the root directory of your Laravel Project run this command.

[cc lang=”bash”]
php composer.phar require intervention/image
[/cc]

Once is complete, that’s it, now you are ready to use the library.

How to use it

In a nutshell

[cc lang=”php” tab_size=”2″ lines=”10″ width=”500″]
use Intervention\Image\ImageManagerStatic as Image;

$originalPath = self::getOriginalPath($imageUri);
$thumbPath = self::getThumbPath($imageUri);
$img = Image::make($originalPath);
$img->widen(300);
$img->save($thumbPath);
[/cc]

What I did

I have created a Thumbs Class where I have a method uri, this method with the uri of the original image (/image/2015/01/myimage.png), will create a thumb if is not already created and then will return the uri to the thumb (/thumb/2015/01/myimage.png).

This is the class

[cc lang=”php” tab_size=”2″ lines=”80″ width=”500″]
widen(300);
$img->save($thumbPath);
}
}
[/cc]

To use it, in the templates I just did this

[cc lang=”php” tab_size=”2″ lines=”3″ width=”500″]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.