Search code examples
image-resizing

How can I resize image with quality without saving image in Python?


I use this code but it need to save

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))
image = img.resize((W, H), Image.ANTIALIAS)
image.save('De7k.jpeg', optimize=True, quality=Quality)

Solution

  • If you would like to "save" the file while keeping it in memory instead of writing a file to disk, you can write it to another BytesIO object.

    from PIL import Image
    import requests
    from io import BytesIO
    
    response = requests.get(url)
    img = Image.open(BytesIO(response.content))
    image = img.resize((W, H), Image.ANTIALIAS)
    output = BytesIO()
    image.save(output, format="JPEG", optimize=True, quality=Quality)