-
-
Save jnbn/7c01097033df662ca0ffaea0537d5682 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 hidden or 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 sys | |
import glob | |
# Trim all png images with alpha in a folder | |
# Usage "python PNGAlphaTrim.py ../someFolder" | |
try: | |
folderName = sys.argv[1] | |
except : | |
print("Usage: python PNGPNGAlphaTrim.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 | |
imageBox = image.getbbox() | |
imageComponents = image.split() | |
if len(imageComponents) < 4: continue #don't process images without alpha | |
rgbImage = Image.new("RGB", imageSize, (0,0,0)) | |
rgbImage.paste(image, mask=imageComponents[3]) | |
croppedBox = rgbImage.getbbox() | |
if imageBox != croppedBox: | |
cropped=image.crop(croppedBox) | |
print(filePath, "Size:", imageSize, "New Size:",croppedBox) | |
cropped.save(filePath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment