A
A
aqau1232022-02-21 02:12:13
Image processing
aqau123, 2022-02-21 02:12:13

How to resize an image without losing quality in python?

I have a script that saves screenshots of posts for the past week, you need to push the screenshots into the Word => first you need to reduce them.

There is this code:

from PIL import Image
from concurrent.futures import ThreadPoolExecutor
from scripts import config
import os

def imageResize(imagePath: str):
    image = Image.open(imagePath)

    newImagePath = os.path.join(os.getcwd(), 'debugScreens', imagePath.split('\\')[-1])

    width, height = image.size

    if height < 400:
        image.save(newImagePath)
        return
    
    desiredHeight = 470

    newWidth = round((desiredHeight * width) / height)

    resizedImage = image.resize((newWidth, desiredHeight))

    resizedImage.save(newImagePath)

    print(f'Saved image: {newImagePath}')

    return

paths = [os.path.join(config.SCREENSHOTS, imgName) for imgName in os.listdir(config.SCREENSHOTS)]

with ThreadPoolExecutor(max_workers=6) as pool:
    pool.map(imageResize, paths)

I also tried other options, but the essence is the same, the output image loses quality.
Image at the input
6212ca81a7d00917921532.jpeg
At the output
6212ca8d977d0275571402.jpeg
How can I make sure that the quality is lost as little as possible.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rPman, 2022-02-21
@rPman

image.save(filename, 'JPEG', quality=90)
where 90 - quality from 0 to 100, default
75 format, you can store photos but not so efficiently)
the examples given are best stored in png

D
Dr. Bacon, 2022-02-21
@bacon

When resizing, the text will almost always be blurred, if possible, then split - separately resize the image, and only then overlay the text

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question