Last Updated: February 25, 2016
· gourneau

Use Python and PIL to slice an image vertically

Say you have a really long picture like this.


And now you want to slice it up into smaller bits, because it is so long.

Here is a Python script that will do that. This was useful to me for in preparing very long images for LaTeX docs.

from __future__ import division
import Image
import math
import os

def long_slice(image_path, out_name, outdir, slice_size):
    """slice an image into parts slice_size tall"""
    img =
    width, height = img.size
    upper = 0
    left = 0
    slices = int(math.ceil(height/slice_size))

    count = 1
    for slice in range(slices):
        #if we are at the end, set the lower bound to be the bottom of the image
        if count == slices:
            lower = height
            lower = int(count * slice_size)  

        bbox = (left, upper, width, lower)
        working_slice = img.crop(bbox)
        upper += slice_size
        #save the slice, "slice_" + out_name + "_" + str(count)+".png"))
        count +=1

if __name__ == '__main__':
    long_slice("longcat.jpg","longcat", os.getcwd(), 300)

This is is the output