views:

44

answers:

1

Hi. I am trying to resize an image before it gets saved. I am using a custom save method on the model, but I've hit a snag.

This is the code I have now:

class UserImages(models.Model):
    height = models.CharField(blank=True, max_length=100)
    width = models.CharField(blank=True, max_length=100)
    image = models.ImageField(upload_to="UserImages/%Y/%m/%d", height_field='height', width_field='width')
    owner = models.ForeignKey(User)

    def __unicode__(self):
        return str(self.image)
    def save(self, *args, **kwargs):
        if self.image:
            filename = str(self.image.path)
            img = Image.open(filename)

            if img.mode not in ('L', 'RGB'):
                img = img.convert('RGB')

            img = ImageOps.fit(img, (180,240), Image.ANTIALIAS, 0, (0.5, 0.5))
            img.save(self.image.path)
        super(UserImages, self).save(*args, **kwargs)

This fails and tells me that the file cannot be found. As far as I can tell, it has to do with the fact that the image so far only exists in memory and therefore cannot be opened like this.

So my question is: How du I open the image from memory and save it back to memory so the default save method can do its thing with it?

Many thanks for any help, this is driving me up the wall :)

+1  A: 

You'll need so save your UserImages before you try to access its ImageField.

An example how to do this can be found in this snippet:

Basically:

super(UserImages, self).save()

PS. You model should have a singular name, e.g. UserImage instead of UserImages.

The MYYN
Many thanks. Thought about saving first, but then forgot about it again. No idea why. And thanks for the headsup on the name. I keep naming all my models in plural, this one must have slipped through the last check :)
Mathias Nielsen