Last active
February 8, 2024 18:53
-
-
Save thomastweets/c7680e41ed88452d3c63401bb35116ed to your computer and use it in GitHub Desktop.
Python script to trim all png images with white background 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
import Image | |
import sys | |
import glob | |
import ImageOps | |
# Trim all png images with white background in a folder | |
# Usage "python PNGWhiteTrim.py ../someFolder" | |
try: | |
folderName = sys.argv[1] | |
except : | |
print "Usage: python PNGWhiteTrim.py ../someFolder" | |
sys.exit(1) | |
filePaths = glob.glob(folderName + "/*.png") #search for all png images in the folder | |
for filePath in filePaths: | |
image=Image.open(filePath) | |
image.load() | |
imageSize = image.size | |
# remove alpha channel | |
invert_im = image.convert("RGB") | |
# invert image (so that white is 0) | |
invert_im = ImageOps.invert(invert_im) | |
imageBox = invert_im.getbbox() | |
cropped=image.crop(imageBox) | |
print filePath, "Size:", imageSize, "New Size:", imageBox | |
cropped.save(filePath) |
Great script! Thanks!
Thanks! This is great!
Thanks a lot, it works great for my case.
Has anyone considered this answer as well? Just checking if there is a unified answer between sites
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well done, thanks!