Skip to content

Instantly share code, notes, and snippets.

@stevenctl
Created August 5, 2019 16:28
Show Gist options
  • Save stevenctl/cc591c6a579353221e144245c0fa0783 to your computer and use it in GitHub Desktop.
Save stevenctl/cc591c6a579353221e144245c0fa0783 to your computer and use it in GitHub Desktop.
Image Splitter
#!/usr/bin/env python
from PIL import Image
image = Image.open("base.png")
def is_empty(line):
for x in range(line.width):
r, g, b, a = line.getpixel((x, 0))
if r + g + b + a > 0:
return False
return True
def crop_rows(im):
minY = 0
was_full = False
rows = []
for y in range(im.height):
line = im.crop((0, y, im.width, y + 1))
full = not is_empty(line)
if not full and was_full:
rows.append(im.crop((0, minY, im.width, y)))
elif full and not was_full:
minY = y
was_full = full
return rows
rows = crop_rows(image)
n = 0
for row in rows:
rot = row.transpose(Image.ROTATE_90).transpose(Image.FLIP_TOP_BOTTOM)
tiles = crop_rows(rot)
for t in tiles:
r,g,b,a = t.resize((1,1)).getpixel((0,0))
if r + g + b + a > 0:
f = t.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)
f.save("%s_%sx%s.png" % (n, f.width, f.height), "PNG")
n += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment