【发布时间】:2019-03-17 09:49:54
【问题描述】:
早安,
我正在使用 Pillow 在名为 Post 的 Django 模型中调整和保存图像的大小。图片是从imagefield中取出来的,get一下是不是RGB的,如果不是就转成RGB。
最后,我从原始图像创建一个缩略图并尝试将其保存在 MEDIA_ROOT 中。
即使图像已上传,它似乎也没有将图像转换为 jpeg。
我按照Django 2+ edit images with Pillow 此处的教程进行操作,并且正在努力满足我的需求。
我在这里错过了什么?
models.py
import os
from django.core.validators import RegexValidator
from django.db import models
from django.utils import timezone
from PIL import Image
from django.conf import settings
from django.db.models.signals import post_save
class Post(models.Model):
# Custom validators
title_validator_specialchar = RegexValidator(regex=r'^[\s*\d*a-zA-Z]{5,60}$', message="The title can't contain any special characters")
category = models.ForeignKey('Category',default=1, on_delete=models.SET_NULL, null=True)
type = models.CharField(max_length=20)
title = models.CharField(max_length=200, validators=[title_validator_specialchar])
content = models.TextField(max_length=2000)
image = models.ImageField(upload_to='%Y/%m/%d/', blank=True)
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField(default=timezone.now)
def save(self, *args, **kwargs):
#On save, update timestamp date created
if not self.id:
self.created_at = timezone.now()
self.updated_at = timezone.now()
return super(Post, self).save(*args, **kwargs)
def __str__(self):
return self.title
def resize_image(instance, **kwargs):
if instance.image:
# we are opening image with Pillow
img = Image.open(instance.image)
# convert image to RGB
if img.mode not in ('L', 'RGB'):
img = img.convert('RGB')
# img.size is tuple with values (width, height)
if img.size[0] > 320 or img.size[1] > 640:
# Using thumbnail to resize image but keep aspect ratio
img.thumbnail((320, 640), Image.ANTIALIAS)
# saving to original place
# instance.image.name is in %Y/%m/%d/<name> format
output = os.path.join(settings.MEDIA_ROOT, instance.image.name)
img.save(output, "JPEG")
# Connect the signal with our model
post_save.connect(resize_image, Post)
【问题讨论】:
标签: django forms image upload python-imaging-library