Skip to content

Instantly share code, notes, and snippets.

@dclamage
Created August 12, 2024 03:35
Show Gist options
  • Save dclamage/5c84ca5f20cb9d706daea90338f45875 to your computer and use it in GitHub Desktop.
Save dclamage/5c84ca5f20cb9d706daea90338f45875 to your computer and use it in GitHub Desktop.
Create vertical images
from PIL import Image
import glob
import os
def resize_and_center_image(input_image_path, output_image_path):
# Open the input image
img = Image.open(input_image_path)
# Calculate the new height preserving the aspect ratio
aspect_ratio = img.height / img.width
new_width = 800
new_height = int(new_width * aspect_ratio)
# Resize the image
img_resized = img.resize((new_width, new_height), Image.ANTIALIAS)
# Create a new image with a transparent background
new_img = Image.new("RGBA", (1080, 1920), (255, 0, 0, 0))
# Calculate the position to center the resized image
x = (1080 - new_width) // 2
y = (1920 - new_height) // 2
# Paste the resized image onto the transparent background
new_img.paste(img_resized, (x, y), img_resized)
# Save the output image
new_img.save(output_image_path)
def process_all_pngs_in_directory(directory):
# Find all PNG files in the directory
png_files = glob.glob(os.path.join(directory, "*.png"))
for input_image_path in png_files:
# Generate a new output path by adding a suffix before the file extension
base, ext = os.path.splitext(input_image_path)
output_image_path = f"{base}-vertical{ext}"
resize_and_center_image(input_image_path, output_image_path)
print(f"Processed {input_image_path} and saved as {output_image_path}")
# Example usage
process_all_pngs_in_directory(".")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment