Craft Beetle
IMAGE COMPRESSION
In an effort to minimize storage space, maximize loading times, and make the website generally more uniform and standardized I created this script which resizes images, compressed them and formats them as webp, bakes in image rotation, and strips them of metadata for my privacy.
from PIL import Image, ExifTags
import os
# Define the input and output directories
folders = ["blog_preview", "blog", "wiki_preview", "wiki", "books", "crafts", "ecology", "films", "game_dev", "games", "micro-blog", "projects", "shows"]
image_width = [ 100, 600, 100, 600, 150, 600, 600, 150, 200, 150, 600, 600, 150]
for index, folder in enumerate(folders):
input_dir = '*/images_original/' + folder + '_original/'
output_dir = '*/images/' + folder + '/'
# Create the output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Set the desired width
desired_width = image_width[index]
# Loop through all files in the input directory
for filename in os.listdir(input_dir):
# Check if the file is an image (you can add more extensions if needed)
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
# Open the image
image_path = os.path.join(input_dir, filename)
image = Image.open(image_path)
# Apply rotation based on EXIF orientation
try:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
exif = image._getexif()
if exif is not None:
orientation_value = exif.get(orientation)
if orientation_value == 3:
image = image.rotate(180, expand=True)
elif orientation_value == 6:
image = image.rotate(270, expand=True)
elif orientation_value == 8:
image = image.rotate(90, expand=True)
except (AttributeError, KeyError, IndexError):
# No EXIF data or orientation not found
pass
# Convert to RGBA if it's a palette image
if image.mode == 'P':
image = image.convert('RGBA')
# Create a new black background
black_background = Image.new('RGBA', image.size, (0, 0, 0, 255))
# Ensure the image has an alpha channel for pasting
if image.mode != 'RGBA':
image = image.convert('RGBA')
# Paste the original image onto the black background
black_background.paste(image, (0, 0), image.split()[3]) # Use the alpha channel as the mask
# Convert to RGB for saving in WebP format
image = black_background.convert('RGB')
# Calculate the new height to maintain aspect ratio
aspect_ratio = image.height / image.width
new_height = int(desired_width * aspect_ratio)
# Resize the image using LANCZOS filter for high-quality downsampling
resized_image = image.resize((desired_width, new_height), Image.LANCZOS)
# Save the resized image in WebP format without metadata
output_filename = os.path.splitext(filename)[0] + '.webp'
resized_image.save(os.path.join(output_dir, output_filename), 'webp', optimize=True, quality=80)
print(folder + " image compression completed.")
print("All image compression completed.")
ยฉ 2024-2026 Craft Beetle | All rights reserved