Skip to content

Instantly share code, notes, and snippets.

@koldunovn
Forked from thomastweets/PNGWhiteTrim.py
Created August 19, 2020 17:56
Show Gist options
  • Save koldunovn/39e7bf3d3dde70cf12fc28ab443d1157 to your computer and use it in GitHub Desktop.
Save koldunovn/39e7bf3d3dde70cf12fc28ab443d1157 to your computer and use it in GitHub Desktop.
Python script to trim all png images with white background in a folder
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment