Answer the question
In order to leave comments, you need to log in
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)
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
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.
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')
{% 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 questionAsk a Question
731 491 924 answers to any question