jason
jason

Reputation: 3075

Django ImageField Setting a Fixed Width and Height

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

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")

Upvotes: 4

Views: 11955

Answers (1)

catherine
catherine

Reputation: 22808

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)

Upvotes: 4

Related Questions