Skip to content

Instantly share code, notes, and snippets.

@ztffn
Created February 26, 2024 05:59
Show Gist options
  • Save ztffn/6cf956c462f6004e64b675774b9a260a to your computer and use it in GitHub Desktop.
Save ztffn/6cf956c462f6004e64b675774b9a260a to your computer and use it in GitHub Desktop.
Tiny Python script that resizes the images in all subfolders to a target size and converts it to PNG format.
# This script is used for resizing and converting images in a specified directory. It traverses through the directory,
# and for each image file it finds (with extensions .png, .jpg, .jpeg, .bmp, .gif, .tiff, .tif), it resizes the image
# to a target size (default is 1024x1024) and converts it to PNG format.
from PIL import Image
import os
def resize_and_convert_images(root_dir, target_size=(1024, 1024)):
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.tif')):
try:
# Construct the full file path
file_path = os.path.join(root, file)
# Open the image
img = Image.open(file_path)
# Preserve alpha channel if present
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
# Convert to RGBA to preserve transparency
img = img.convert('RGBA')
new_img = Image.new("RGBA", target_size, (255, 255, 255, 0))
img.thumbnail(target_size, Image.Resampling.LANCZOS) # Updated resampling filter
new_img.paste(img, (int((target_size[0] - img.size[0]) / 2), int((target_size[1] - img.size[1]) / 2)))
else:
# Resize without preserving transparency, using updated resampling filter
img = img.resize(target_size, Image.Resampling.LANCZOS)
# Construct the new file name and path
new_file_name = os.path.splitext(file)[0] + "_lowres.png"
new_file_path = os.path.join(root, new_file_name)
# Save the resized image as a PNG file
img.save(new_file_path, "PNG")
print(f"Processed and saved: {new_file_path}")
# Delete the original file
os.remove(file_path)
print(f"Deleted original file: {file_path}")
except Exception as e:
print(f"Error processing {file_path}: {e}")
if __name__ == "__main__":
# Replace '/path/to/your/folder' with the path to the folder you want to process
# root_dir = '/path/to/your/folder'
# Or run it on the script location folder
root_dir = os.getcwd()
resize_and_convert_images(root_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment