Skip to content

Instantly share code, notes, and snippets.

@MaherSaif
Forked from kitze/trim.py
Created March 17, 2024 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaherSaif/a89ea83e80e3413e09f76392a0e35d60 to your computer and use it in GitHub Desktop.
Save MaherSaif/a89ea83e80e3413e09f76392a0e35d60 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