[Answer]-How to use Django to resize a user's image and upload to Amazon S3?

1👍

Try using the following instead:

def save(self):
    image = Image.open(self.full_image_large)
    (w, h) = image.size
    r900 = 900.0/w
    im900 = image.resize((int(math.floor(r900*w)), int(math.floor(r900*h))), Image.ANTIALIAS)
    im900.save(self.full_image_large)

    r350 = 350.0/w
    im350 = image.resize((int(math.floor(r350*w)), int(math.floor(r350*h))), Image.ANTIALIAS)
    im350.save(self.full_image)

    r120 = 120.0/w
    im120 = image.resize((int(math.floor(r120*w)), int(math.floor(r120*h))), Image.ANTIALIAS)
    im120.save(self.thumbnail_image)

    super(Artwork, self).save()

You can do all three resize operations on the same Image instance – image in this case. Just save the results of that operation in a new object for each size, then save that object instead of saving the original image object.

However, one of Python’s main tenets is DRY – Don’t Repeat Yourself. The above code can be refactored like so:

def save(self):
    image = Image.open(self.full_image_large)
    (w, h) = image.size
    for width, target in zip([900.0, 350.0, 120.0], 
                             [self.full_image_large, 
                              self.full_image, 
                              self.thumbnail_image]):
        r = width/w
        im = image.resize((int(math.floor(r*w)), 
                           int(math.floor(r*h))), 
                           Image.ANTIALIAS)
        im.save(target)

    super(Artwork, self).save()

zip creates a tuple of each width and target.

Leave a comment