Django ImageField设置固定宽度和高度 [英] Django ImageField Setting a Fixed Width and Height

查看:2204
本文介绍了Django ImageField设置固定宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following image field in my models.py (see code below)

我想设置固定宽度图像的高度,所以它总是100x100px

I would like to set a fixed width and height of the image so its always 100x100px

下面的代码是系统中已经有的,我不知道如何传递宽度和高度,或者如果这个代码可以用于将宽度和高度设置为修剪大小。

The code below is what was already in the system, I'm not sure how width and height gets passed or if this code can be used to set the width and height to a fix size.

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设置固定宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆