P
P
Pan Propan2016-03-17 00:44:26
Django
Pan Propan, 2016-03-17 00:44:26

How to get an image of different sizes in Django?

I am using the Pil library

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)
from PIL import Image

class User(AbstractBaseUser):
    logo = models.ImageField(upload_to='logo/', verbose_name="Логотип компании", null=True)
    def save(self):
        if not self.id and not self.logo:
            return

        super(User, self).save()
        image = Image.open(self.logo)
        image.thumbnail((250,150), Image.ANTIALIAS)
        image.save(self.logo.path+'thumbnail_200_200_aa.jpg', 'JPEG', quality=75)

Above, I overwrite the uploaded image, and I need to make two more variations of imageresize and imagethumbnail in addition to the original.
It's all done like this:
def get_image_resize(self):
    image = Image.open(self.logo)
    imageresize = image.resize((500,500), Image.ANTIALIAS)
    imageresize.save('resize_500_500_aa.jpg', 'JPEG', quality=75)
   #Как  в шаблоне  получить ссылку на сохраненное изображение?
   
def get_image_thumbnail(self):
    image = Image.open(self.logo)
    imagethumbnail = image.thumbnail((200,200), Image.ANTIALIAS)
    imagethumbnail.save('thumbnail_200_200_aa.jpg', 'JPEG', quality=75)
   #Как  в шаблоне  получить ссылку на сохраненное изображение?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2016-03-17
@mgis

There is a wonderful imagekit library that allows you to generate previews either on the fly or store them in a database. Both are done in one line.

V
Viktor Melnikov, 2016-03-17
@Viteran33

You can immediately do this in the template using the sorl-thumbnail
model

from sorl.thumbnail import ImageField
class MyModel(models.Model):
    image = models.ImageField(upload_to='/dev/null')

output in a template with given dimensions
{% thumbnail item.image "100x100" crop="center" as im %}
    <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question