Sven Hendriks avatar Sven Hendriks committed 35a3bdd

Added --ycenter option.

Comments (0)

Files changed (1)

 import sys
 import optparse
+import math
 
 import Image
 
 RATIO = (4, 3)
 
-def slice_image(input_filename, slice_width=None, center=False):
+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)
 
-    offset = (slice_width - im.size[0] % slice_width) / 2 if center else 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
 
-    for i, x in enumerate(range(-offset, im.size[0], slice_width)):
-        tile = im.crop((x, 0, x + slice_width, im.size[1]))
+    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()
 
 if __name__ == '__main__':
     parser = optparse.OptionParser()
-    parser.add_option('--center', action='store_true', dest='center', default=False, help='Center')
+    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.center)
+            slice_image(args[0], int(args[1]), opts.x_center, opts.y_center)
         else:
-            slice_image(args[0], center=opts.center)
+            slice_image(args[0], x_center=opts.x_center, y_center=opts.y_center)
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.