Skip to content

Instantly share code, notes, and snippets.

@kitze
Created April 6, 2023 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kitze/f078c38a84f6c9b1f524806fc0e819aa to your computer and use it in GitHub Desktop.
Save kitze/f078c38a84f6c9b1f524806fc0e819aa to your computer and use it in GitHub Desktop.
trim blank space around images in a folder
from PIL import Image
import os
input_folder = "./public/old"
output_folder = "./public"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.endswith(".png"):
image_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)
with Image.open(image_path) as image:
# Convert the image to RGBA mode if necessary
if image.mode != "RGBA":
image = image.convert("RGBA")
# Check if the alpha channel exists
if "A" not in image.getbands():
continue
# Separate the RGBA channels
r, g, b, a = image.split()
# Find the bounding box of the non-blank pixels in the alpha channel
bbox = a.getbbox()
if bbox:
# Crop the image using the bounding box
cropped_image = image.crop(bbox)
cropped_image.save(output_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment