Extracting Tiles

Today I was looking through OpenGameArt for readymade character sprites to use in the Isogame project and found that the spritesheets were all compilations of multiple sprites instead of discrete files.

For a prototype I find that using separate files is easier in the first iteration, but extracting by hand is too tedious so I thought I’d use Imagemagick and Python to do that.

For Mac, Imagemagick is available on homebrew as:

brew install imagemagick

The python script uses five parameters, the width and height of the image, the amount of vertical (rows) and horizontal (columns) tiles as well as the filename.

For spritesheets I thought I’d use this one to begin with.


import subprocess
import sys

#width = 2048
#height = 2048
#rows = 8
#columns = 8
#filename = "filename.png"

def crop(w, h, x, y, fn, fnp, r, c):
    command = 'convert {} -crop {}x{}+{}+{} {}_{}_{}.png'.format(fn, w, h, x, y, fnp, r, c)

def cropAll(width, height, rows, columns, filename):
    tileheight = height / rows;
    tilewidth = width / columns;
    fnp = filename.split(".")[0]    
    for r in range(rows):
        for c in range(columns):
            crop(tilewidth, tileheight, c * tilewidth, r * tileheight, filename, fnp, r, c)

w = int(sys.argv[1])
h = int(sys.argv[2])
r = int(sys.argv[3])
c = int(sys.argv[4])
fn = sys.argv[5]
cropAll(w, h, r, c, fn)