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