How to correctly resize and rename upladed image in 'save' method?

# Here is our model:
class Product(models.Model):
    # some fields
    photo = models.ImageField(upload_to='images',
verbose_name=u'zdjęcie', null=True, blank=True)

# and here we are our save method:
    def save(self, *args, **kwargs):
        if self.photo:
            image = Image.open(self.photo)
            if image.mode not in ('L', 'RGB'):
                image = image.convert('RGB')
            image.thumbnail(settings.UPLOADED_IMAGES_SIZE,
Image.ANTIALIAS)
            self.photo.open()
            image.save(self.photo, 'PNG')
            self.photo.name = '%s.png' % os.path.splitext
(self.photo.name)[0]
        super(Product, self).save(*args, **kwargs)

everything working but self.photo size(in bytes not width and height)
is wrong(it no changed after resizing), and if we download that image
it have previous size, so i try do it this way:

    def save(self, *args, **kwargs):
        if self.photo:
            image = Image.open(self.photo)
            if image.mode not in ('L', 'RGB'):
                image = image.convert('RGB')
            image.thumbnail(settings.UPLOADED_IMAGES_SIZE,
Image.ANTIALIAS)
            tmp_file = StringIO()
            image.save(tmp_file, 'PNG')
            self.photo.open()
            tmp_file.seek(0)
            self.photo.write(tmp_file.read())
            del image
            self.photo.name = '%s.png' % os.path.splitext
(self.photo.name)[0]
            # now we have correct image size but i don't know how to
assign it to our image:
            # i can't asign it that:
            self.photo.size = tmp_file.len
        super(Product, self).save(*args, **kwargs)

Anybody know how to solve it?

Łukasz Fidosz
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to