4

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")
Aaron Lelevier
  • 19,850
  • 11
  • 76
  • 111
jason
  • 2,895
  • 8
  • 26
  • 38
  • Do you want to resize the image down when it's first uploaded or just always display it at 100x100? Also, are you sure the images all have a 1:1 aspect ratio? If not, you might want to resize at upload and set whichever dimension is larger to 100 and preserve the aspect ratio. – Tom Feb 28 '13 at 16:37
  • I want the image to be re-sized on upload to 100x100 not scaled down on display, sorry i should have made that clear. – jason Feb 28 '13 at 16:38
  • Probably want to unmark the answer below then. [This link](http://davedash.com/2009/02/21/resizing-image-on-upload-in-django/) should show you how to do it in a view, this [SO thread](http://stackoverflow.com/questions/623698/resize-image-on-save) provides another approach. I usually do this in the model's save() method. – Tom Feb 28 '13 at 20:06

1 Answers1

4
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)
catherine
  • 22,492
  • 12
  • 61
  • 85