Creating tiles from an image with Python and PIL 0 Comments

I purchased the Beta Book version of this morning and have been working my way through the Google Maps example they have. Unfortunately they provide the source for a small java program to actually cut your big map image down into little tiles. I decided I could not be bothered to download and install a JVM , so I created my own little script in using the PIL library to create the tile images required. With very little effort it could become a generic image splitter. The resulting images are saved as pngs by default.

Heres the source


 import Image
 import sys

 image = Image.open(sys.argv[1])
 tile_width = int(sys.argv[2])
 tile_height = int(sys.argv[3])
 zoom_level = sys.argv[4]

 if image.size[0] % tile_width == 0 and image.size[1] % tile_height ==0 :
 	currentx = 0
 	currenty = 0
 	while currenty < image.size[1]:
 		while currentx < image.size[0]:
 			print currentx,",",currenty
 			tile = image.crop((currentx,currenty,currentx + tile_width,currenty + tile_height))
 			tile.save("x" + str(currentx) + "y" + str(currenty) + "z" + zoom_level + ".png","PNG")
 			currentx += tile_width
 			currenty += tile_height
 			currentx = 0
 else:
 	print "sorry your image does not fit neatly into",tile_width,"*",tile_height,"tiles"



Add Comment

Comments