Skip to content

Instantly share code, notes, and snippets.

@trojanfoe
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trojanfoe/9255303 to your computer and use it in GitHub Desktop.
Save trojanfoe/9255303 to your computer and use it in GitHub Desktop.
Python script to split an image into vertical slices. Useful for processing background images (i.e. cocos2d, etc.)
#!/usr/bin/env python
#
# Slice an image into the specified number of vertical slices.
#
# Usage: vslice.py [options] image output-path num-slices
# Use --help for a list of options.
#
# Andy Duplain <trojanfoe@gmail.com> 26-Feb-2014
#
import sys, os
from optparse import OptionParser
from PIL import Image
progName = None
def vslice(inputName, outputPath, baseName, numSlices, options):
if options.zeroFill:
outputFileFormat = "{0}-{1:03d}.png"
else:
outputFileFormat = "{0}-{1}.png"
image = Image.open(inputName)
width, height = image.size
sliceWidth = width / numSlices
print "{0}: Image size={1}x{2}, slice width={3}".format(progName, width, height, sliceWidth)
if sliceWidth * numSlices != width:
print "{0}: Number of slices does not fit exactly ({1} != {2})".format(progName, sliceWidth * numSlices, width)
for i in range(0, numSlices):
# Box is (left, upper, right, bottom) and NOT (x, y, width, height)...
x = sliceWidth * i
box = (x, 0, x + sliceWidth, height)
slice = image.crop(box)
slice.load()
if options.cropOutput:
outputImage = Image.new(image.mode, (sliceWidth, height))
outputImage.paste(slice, (0, 0, sliceWidth, height))
else:
outputImage = Image.new(image.mode, (width, height))
outputImage.paste(slice, box)
outputName = os.path.join(outputPath, outputFileFormat.format(baseName, i + 1))
outputImage.save(outputName, "PNG")
print "{0}: Saved slice {1} to {2}".format(progName, i + 1, outputName)
return True
def main():
global progName
progName = os.path.basename(sys.argv[0])
parser = OptionParser("usage: %prog [options] image output-path num-slices")
parser.add_option("-c", "--crop-output", dest="cropOutput", action="store_true", default=False, help="Crop output image to slice")
parser.add_option("-z", "--zero-fill", dest="zeroFill", action="store_true", default=False, help="Zero-fill numbered output filenames")
(options, args) = parser.parse_args()
if len(args) != 3:
parser.error("Incorrect number of arguments")
inputName = args[0]
outputPath = args[1]
numSlices = int(args[2])
if numSlices < 2:
parser.error("Incorrect number of slices")
if not os.path.exists(outputPath):
os.mkdir(outputPath)
baseName = os.path.splitext(inputName)[0]
vslice(inputName, outputPath, baseName, numSlices, options)
print "{0}: Done.".format(progName)
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment