开发者

model save method. Resize image before save

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


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:

  • http://djangosnippets.org/snippets/1100/

Basically:

super(UserImages, self).save()

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


Use django-resized

pip install django-resized

models.py

from django_resized import ResizedImageField

class MyModel(models.Model):
    ...
    image = ResizedImageField(max_width=500, max_height=300, upload_to='whatever')

For more info look at https://github.com/un1t/django-resized

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜