import Image
import ImageDraw
import sys

def floodfill(image, xy, value):
    "Fill bounded region."
    # based on an implementation by Eric S. Raymond
    pixel = image.load()
    x, y = xy
    try:
        background = pixel[x, y]
        if background == value:
            return # seed point already has fill color
        pixel[x, y] = value
    except IndexError:
        return # seed point outside image
    edge = [(x, y)]
    while edge:
        newedge = []
        for (x, y) in edge:
            for (s, t) in ((x+1, y), (x-1, y), (x, y+1), (x, y-1), (x+1,y+1),(x+1,y-1),(x-1,y-1),(x-1,y+1)):
                try:
                    p = pixel[s, t]
                except IndexError:
                    pass
                else:
                    if p == background:
                        pixel[s, t] = value
                        newedge.append((s, t))
        edge = newedge

def bounds(im):
    s = [(x,y) for x in range(im.size[0]) for y in range(im.size[1]) if im.getpixel((x,y))]
    xs = [x for (x,y) in s]
    ys = [y for (x,y) in s]
    return (min(xs), min(ys), max(xs) + 1, max(ys) + 1)

sheet = Image.new("RGBA", (16, 16 * 47))
im = Image.open("pickups.png")
a = im.split()[3]
i = 0
for y in range(im.size[1]):
    for x in range(im.size[0]):
        if a.getpixel((x, y)) == 255:
            floodfill(a, (x,y), 127)
            matte = Image.eval(a, lambda a: 255 if a == 127 else 0)
            sprite = im.crop(bounds(matte))
            if sprite.size[0] <= 16 and sprite.size[1] <= 16:
                # sprite.save("preview%03d.png" % i)
                (w, h) = sprite.size
                sheet.paste(sprite, ((16 - w) / 2, (16 * i) + (16 - h) / 2))
                print i
                i += 1
            a = Image.eval(a, lambda a: 255 if a == 255 else 0)
sheet.save("preview.png")
