Source

panslice / panslice.py

Full commit
import sys
import optparse
import math

import Image

RATIO = (4, 3)

def slice_image(input_filename, slice_width=None, x_center=False, y_center=False):
    im = Image.open(input_filename)

    if not slice_width:
        slice_width = int((im.size[1] / 3.0) * 4.0)

    if y_center:
        d, r = divmod(im.size[0], slice_width)
        x_correction = float(r) / float(d)
        y_offset = int(round(((((slice_width + x_correction) / 4.0) * 3.0 - im.size[1]) / 2.0)))
        slice_width += int(math.ceil(x_correction))
    else:
        y_offset = 0

    x_offset = (slice_width - im.size[0] % slice_width) / 2 if x_center and not y_center else 0

    for i, x in enumerate(range(-x_offset, im.size[0], slice_width)):
        tile = im.crop((x, -y_offset, x + slice_width, im.size[1]+y_offset))
        tile.save('%s_tile_%02d.jpg' % (input_filename, (i+1)), quality=95)
        sys.stdout.write('.')
        sys.stdout.flush()
    print

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option('--xcenter', action='store_true', dest='x_center', 
                      default=False, help='x center')
    parser.add_option('--ycenter', action='store_true', dest='y_center', 
                      default=False, help='y center (takes precedence over x center)')
    opts, args = parser.parse_args()

    if len(args) not in (1, 2):
        sys.exit('Usage: %s [options] <input file> [<slice width>]' % (sys.argv[0],))
    else:
        if len(args) == 2:
            slice_image(args[0], int(args[1]), opts.x_center, opts.y_center)
        else:
            slice_image(args[0], x_center=opts.x_center, y_center=opts.y_center)