Django Sorl Thumbnail A Few Tricks

By Samuel Muiruri | Oct. 25, 2019 | Django


I normally use Sorl-Thumbnail when it comes to image manipulation, I like the cropping part where you can give it some dimensions like "2400x800" and position "center" and it will crop that section from an image.

Pretty useful tool for web development, then lately I've worked on a site that is pretty image heavy, I'm talking of around 11 images on the caurosel not to mention atleast another 10-20 more images average sized still on the same page.

Now one issue I was starting to note is using a set dimensions like "2400x800" wasn't going to cut it because these images tended not to all come in the same dimensions so where one it might take a nice snug cut from the center being close to the edges so it includes most of the content in the image other images were larger so it would feel like you zoomed in to the center and a good portion was really cut out.

So I looked out it it's possible to provide a ratio to sorl like "3:1" and it would try and use as much of that area as possible but sadly for now it can't. I wrote my own script that accomplishes this and here it is.

So this snippet shows how the code works.

And in the templates

{% thumbnail image.image image.get_dimensions|image_dimensions:"3:1" crop="center" as im %} 

and there you go a quick way to use ratio with images.

Another important feature is optisorl this repo works with sorl thumbnail but it optimizes the file size of the images without impacting clarity and the difference in size is amazing.