source: trunk/game/utilities/slicer_pil.py @ 416

Revision 409, 5.1 KB checked in by zenbitz, 10 years ago (diff)

changed tail to minimum 35 px (I hope)

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2
3#   This program is free software: you can redistribute it and/or modify
4#   it under the terms of the GNU General Public License as published by
5#   the Free Software Foundation, either version 3 of the License, or
6#   (at your option) any later version.
7
8#   This program is distributed in the hope that it will be useful,
9#   but WITHOUT ANY WARRANTY; without even the implied warranty of
10#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11#   GNU General Public License for more details.
12
13#   You should have received a copy of the GNU General Public License
14#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16
17import Image
18import getopt
19import logging
20import os
21import sys
22
23log = logging.getLogger("splicer")
24log.setLevel(logging.DEBUG)
25
26def saveSlice(img, filename, num, left, right, slice_width):
27    """ Takes a slice out of the image passed. This slice is defined by
28        left and righ and will be saved as filename extended with num before
29        the prefix.
30        @type img: Image.new
31        @param img: Source image to take the slice from
32        @type filename: String
33        @param filename: Base filename
34        @type num: Integer
35        @param nun: Suffix for the filename
36        @type left: Integer
37        @param left: Left boundary of the slice
38        @type right: Integer
39        @param right: Right boundary of the slice
40        @type slice_width: Integer
41        @param slice_width: The desired width of a slice, trimmed images will be
42        extended to this width.
43        @rtype: Boolean
44        @return True on success, False on failure """         
45
46    # Create the slice
47    copy_image = img.copy()
48
49    # Crop and trim it
50    (width,height) = copy_image.size
51    if (right > width):
52        right = width
53    log.debug("size: %d %d %d %d" % (0,left,right,height))
54    # PIL wants (left, upper, right, lower)
55    new_image = copy_image.crop((left,\
56                                 0,\
57                                 right,\
58                                 height))
59
60    #new_image.trim() - hard to reimplement in PIL
61
62    # Obtain the filename
63    (name,ext) = os.path.splitext(filename)
64    new_filename = name + str(num) + ext
65    log.debug("Going to write slide %d to %s" %(num,new_filename))
66    new_image.save(new_filename)
67    log.info("Wrote %s",new_filename)
68    return True 
69       
70def sliceImage(filename, slice_width=70, tail_width=105):
71    """ Opens an image, and produces slice_width pixel wide slices of it
72        @type filename: String
73        @param filename: Pathname of the image to open
74        @type slice_width: Integer
75        @param slice_width: Width of the slices that should be made
76        @rtype: Bool
77        @return True on success, false on failure. """
78   
79    if not os.path.isfile(filename):
80        log.info("File does not exist: %s", filename)
81        return False
82   
83    img = Image.open(filename)
84    log.debug("Loaded file: %s", filename)
85    (img_width,img_height) = img.size
86    log.debug("Image geometry before trim %dx%d", img_width, img_height)
87   
88    #img.trim()  No trim support in PIL
89    #img_width = img.size.width
90    #img_height = img.size.height
91    #log.debug("Image geometry after trim %dx%d", img_width, img_height)
92   
93    current_pos = 0
94    num = 0
95    while current_pos + slice_width < img_width:
96        remainder = img_width - current_pos
97        log.info("Remainder: %d" % remainder)
98        if remainder < tail_width + slice_width:
99            break
100        # Save the slice
101        if not saveSlice(img, filename, num, current_pos, \
102                         current_pos + slice_width, slice_width):
103            log.info("Failed to save slice: %d", num)
104            return False 
105        num = num + 1
106        current_pos += slice_width
107   
108    # Handle the tail tail is now bigger
109    if(current_pos < img_width):
110        if not saveSlice(img, filename, num, current_pos, \
111                         img_width-1, slice_width):
112            log.info("Failed to save tail slice: %d", num)
113            return False 
114    return True
115   
116def usage():
117    """ Prints the help message. """
118    print "Usage: %s [options]" % sys.argv[0]
119    print "Options:"
120    print "   --verbose, -v      Verbose"
121    print "   --help, -h         This help message"
122    print "   --file FILE, -f    File to splice"
123   
124def main(argv):
125    """ Main function, parses the command line arguments
126    and launches the splicing logic. """
127
128    try:
129        opts, args = getopt.getopt(argv, "hf:v", 
130        ["help","file", "verbose"])
131    except getopt.GetoptError:
132        usage()
133        sys.exit(2)
134       
135    ch = logging.StreamHandler()
136    ch.setLevel(logging.INFO)
137   
138    file = ""
139    for opt, arg in opts:       
140        if opt in ("-f","--file"):
141            file = arg
142        elif opt in ("-v","--verbose"):
143            ch.setLevel(logging.DEBUG)
144        else:
145            usage()
146            sys.exit()
147   
148    formatter = logging.Formatter("%(levelname)s: %(message)s")
149    ch.setFormatter(formatter)
150    log.addHandler(ch)
151   
152    if sliceImage(file, 70, 35):
153        log.info("Done")
154    else:
155        log.info("Aborted")
156   
157if __name__ == '__main__':
158    main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.