Join Login Create a Request

Django resize images to dimensions using Python

from PIL import Image
from io import BytesIO
from django.core.files import File


def reduce_image_size(image, name, height, width):
    img = Image.open(image)

    if img.height > height or img.width > width:
        new_img = (width, height)
        img.thumbnail(new_img)
    thumb_io = BytesIO()
    rgb_im = img.convert('RGB')
    rgb_im.save(thumb_io, 'webp', quality=70)
    new_image = File(thumb_io, name=name+'.webp')
    return new_image

Related Snippets