Python program to resize images

When you first run the Python script, it will create an input and output directory. After the first run of the script, place the image files in the input directory and run the script again. Created files will be in the output directory. Works with files ending in .jpg or .JPG.

import os
from PIL import Image

# Define percentage (e.g., 30% of original size)
percentage = 0.3

#create directories if not exist
os.makedirs("./input", exist_ok=True)
os.makedirs("./output", exist_ok=True)

#iterate through directory
for iFile in os.listdir("./input"):
  #substring of last 4 digits of filename
  if iFile[-4:] in (".jpg", ".JPG"):

    # Load image
    img = Image.open("./input/" + iFile)

    # Calculate new dimensions maintaining aspect ratio
    new_width = int(img.size[0] * percentage)
    new_height = int(img.size[1] * percentage)

    # Resize using high-quality resampling
    resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)

    # Save result
    resized_img.save("./output/" + "z" + iFile)

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *