gpt4 book ai didi

Django ImageField 设置固定宽度和高度

转载 作者:行者123 更新时间:2023-12-03 21:43:33 29 4
gpt4 key购买 nike

我的models.py中有以下图像字段(见下面的代码)

我要图像的固定宽度和高度,所以它总是 100x100px

下面的代码是系统中已有的代码,我不确定宽度和高度是如何传递的,或者此代码是否可用于将宽度和高度设置为固定大小。

image = models.ImageField(
upload_to="profiles",
height_field="image_height",
width_field="image_width",
null=True,
blank=True,
editable=True,
help_text="Profile Picture",
verbose_name="Profile Picture"
)
image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")

最佳答案

class ModelName(models.Model):    
image = models.ImageField(
upload_to="profiles",
null=True,
blank=True,
editable=True,
help_text="Profile Picture",
verbose_name="Profile Picture"
)
image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")

def __unicode__(self):
return "{0}".format(self.image)

def save(self):
if not self.image:
return

super(ModelName, self).save()
image = Image.open(self.photo)
(width, height) = image.size
size = ( 100, 100)
image = image.resize(size, Image.ANTIALIAS)
image.save(self.photo.path)

关于Django ImageField 设置固定宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15140483/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com