Created
April 6, 2023 14:14
-
-
Save kitze/f078c38a84f6c9b1f524806fc0e819aa to your computer and use it in GitHub Desktop.
trim blank space around images in a folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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