Skip to content

Instantly share code, notes, and snippets.

@cppio
Created December 25, 2025 00:16
Show Gist options
  • Select an option

  • Save cppio/adc99be90d2dd73138ed65f669cb25a0 to your computer and use it in GitHub Desktop.

Select an option

Save cppio/adc99be90d2dd73138ed65f669cb25a0 to your computer and use it in GitHub Desktop.
from PIL import Image
def trim(im):
data = list(im.getdata())
cs = set()
w, h = im.size
for x in range(w):
cs.add(data[x])
cs.add(data[(h - 1) * w + x])
for y in range(h):
cs.add(data[y * w])
cs.add(data[y * w + (w - 1)])
[c] = cs
while True:
if all(i == c for i in data[:w]):
del data[:w]
h -= 1
elif all(i == c for i in data[(h - 1) * w:]):
del data[(h - 1) * w:]
h -= 1
elif all(i == c for i in data[::w]):
del data[::w]
w -= 1
elif all(i == c for i in data[w - 1::w]):
del data[w - 1::w]
w -= 1
else:
break
out = Image.new(im.mode, (w, h))
out.putdata(data)
return out
if __name__ == "__main__":
import sys
err = False
for f in sys.argv[1:]:
try:
im = Image.open(f)
im = trim(im)
im.save(f + ".trim.png")
except Exception as e:
print(e, file=sys.stderr)
err = True
if err:
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment