[Django]-Python Resize image with ratio of maximum side of the image

4👍

Do you want to have all images with same width 1000? Try this code. It will resize to at most 1000 as width (if the image’s width is less than 1000, nothing changes)

def image_resize(request,image_id):
    photo = Photo.objects.get(pk=image_id)
    image = Image.open(photo.photo.file)
    (w,h) = image.size
    if (w > 1000):
        h = int(h * 1000. / w)
        w = 1000
    image = image.resize((w, h), Image.ANTIALIAS)
    image.save()

0👍

I recall doing this sometime back without any problem except that I used thumbnail method rather than resize. Try it. You need not assign img to image. You can process img and save the same.

# open img
img.thumbnail((1000,560), Image.ANTIALIAS)
# save img

Leave a comment