Resizing image in Django using sorl-thumbnail

805 views Asked by At

I need to resize an image using the Django app sorl-thumbnail (https://github.com/mariocesar/sorl-thumbnail).

I tried the documentation and the only way to resize an image is by using the template tag but what I want is to change it in a view.

This is because I need to upload a raw image and append the resized image into a modal using jQuery. Is there anyway to achieve this using sorl-thumbnail? I am seeing some solutions in PIL but they seem too complicated.

1

There are 1 answers

0
AlvaroAV On

You can use sorl-thumbnail in your view to resize an image like:

from sorl.thumbnail import get_thumbnail

im = get_thumbnail(your_image, '100x100', crop='center', quality=99)
# ...    ...    ...    ...    ...    ...    ...    ...    ...
# Do whatever you want to do with this new resized image
# e.g.: Send the url of the image to template
# e.g.: return HttpResponse('your_template.html', { 'image_url':im.url, ...}, request...)
  • You can change the 100x100 for your desired Width x Height
  • You can get the url of this thumbnail to use it on your template using: im.url