我需要在保存到数据库之前调整图像大小,所以我覆盖了 save 方法:
from PIL import Image
class Categorias(models.Model):
image_height = models.PositiveIntegerField(editable=False,null=True)
image_width = models.PositiveIntegerField(editable=False,null=True)
the_image = models.ImageField(upload_to="uploads/image/category",width_field="image_width",height_field="image_height")
def save(self):
if not self.id and not self.the_image:
return;
image = Image.open(self.the_image)
ratio_height = (890*self.image_height)/self.image_width
size = (890,ratio_height)
image = image.resize(size, Image.ANTIALIAS)
image.save(self.the_image.path)
图像已调整大小并写入我的媒体文件夹,但问题是注册表未保存在数据库中。
我不知道我错过了什么。
toad013 帮助了我,我可以将注册表保存到数据库中,但随后我将两张图像写入我的媒体文件夹,一张是原始图像,另一张使用以下代码调整大小:
def save(self):
if not self.id and not self.the_image:
return;
image = Image.open(self.the_image)
ratio_height = (890*self.image_height)/self.image_width
size = (890,ratio_height)
image = image.resize(size, Image.ANTIALIAS)
image.save(self.the_image.path)
super(Categorias, self).save()