Posted By

miohtama on 07/11/11


Tagged

image tile bitmap slice crop


Versions (?)

Slicing images with Python and PIL


 / Published in: Python
 

Create smaller tiles out of a larger bitmap image

  1. def process_floor_image(infile, outfile, copy_pics):
  2. """
  3. Copy the orignal image and make also 1024 x 1024 sliced tiles out of it.
  4.  
  5. Because our green robot friend sucks.
  6.  
  7. http://stackoverflow.com/questions/6632140/android-pixel-quality-reduction-in-images-loaded-in-webview
  8.  
  9. @return Image size in [width, height]
  10. """
  11.  
  12.  
  13. im = Image.open(infile)
  14.  
  15. w = im.size[0]
  16. h = im.size[1]
  17. dimensions = [ w, h ]
  18.  
  19. if copy_pics:
  20.  
  21. # Copy master
  22. path = os.path.dirname(outfile)
  23. base = os.path.basename(outfile)
  24.  
  25. try:
  26. os.makedirs(path)
  27. except OSError:
  28. pass
  29.  
  30. print "Copying image:" + outfile
  31. shutil.copyfile(infile, outfile)
  32.  
  33. # slice the image to 1000 x 1000 tiles
  34. slice_size = 1000
  35. for y in range(0, h, slice_size):
  36. for x in range(0, w, slice_size):
  37. fname = os.path.join(path, "tile-%d-%d-%s" % (x, y, base))
  38. print "Creating tile:" + fname
  39.  
  40. mx = min(x+slice_size, w)
  41. my = min(y+slice_size, h)
  42.  
  43. buffer = Image.new("RGB", [slice_size, slice_size], (255, 255, 255))
  44. tile = im.crop((x, y, mx, my))
  45. buffer.paste(tile, (0, 0))
  46. buffer.save(fname, "PNG")
  47.  
  48. return dimensions

Report this snippet  

You need to login to post a comment.