]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wxPython/tools/img2py.py
removed carbon printing code
[wxWidgets.git] / wxPython / wxPython / tools / img2py.py
1 #----------------------------------------------------------------------
2 # Name: wxPython.tools.img2py
3 # Purpose: Convert an image to Python code.
4 #
5 # Author: Robin Dunn
6 #
7 # RCS-ID: $Id$
8 # Copyright: (c) 2002 by Total Control Software
9 # Licence: wxWindows license
10 #----------------------------------------------------------------------
11
12
13 """
14 img2py.py -- Convert an image to PNG format and embed it in a Python
15 module with appropriate code so it can be loaded into
16 a program at runtime. The benefit is that since it is
17 Python source code it can be delivered as a .pyc or
18 'compiled' into the program using freeze, py2exe, etc.
19
20 Usage:
21
22 img2py.py [options] image_file python_file
23
24 Options:
25
26 -m <#rrggbb> If the original image has a mask or transparency defined
27 it will be used by default. You can use this option to
28 override the default or provide a new mask by specifying
29 a colour in the image to mark as transparent.
30
31 -n <name> Normally generic names (getBitmap, etc.) are used for the
32 image access functions. If you use this option you can
33 specify a name that should be used to customize the access
34 fucntions, (getNameBitmap, etc.)
35
36 -c Maintain a catalog of names that can be used to reference
37 images. Catalog can be accessed via catalog and index attributes
38 of the module. If the -n <name> option is specified then <name>
39 is used for the catalog key and index value, otherwise
40 the filename without any path or extension is used as the key.
41
42 -a This flag specifies that the python_file should be appended
43 to instead of overwritten. This in combination with -n will
44 allow you to put multiple images in one Python source file.
45
46 -u Don't use compression. Leaves the data uncompressed.
47
48 -i Also output a function to return the image as a wxIcon.
49
50 """
51
52 #
53 # Changes:
54 # - Cliff Wells <LogiplexSoftware@earthlink.net>
55 # 20021206: Added catalog (-c) option.
56 #
57
58
59 import sys, os, glob, getopt, tempfile
60 import cPickle, cStringIO, zlib
61 import img2img
62 from wxPython import wx
63
64
65 def crunch_data(data, compressed):
66 # compress it?
67 if compressed:
68 data = zlib.compress(data, 9)
69
70 # convert to a printable format, so it can be in a Python source file
71 data = repr(data)
72
73 # This next bit is borrowed from PIL. It is used to wrap the text intelligently.
74 fp = cStringIO.StringIO()
75 data = data + " " # buffer for the +1 test
76 c = i = 0
77 word = ""
78 octdigits = "01234567"
79 hexdigits = "0123456789abcdef"
80 while i < len(data):
81 if data[i] != "\\":
82 word = data[i]
83 i = i + 1
84 else:
85 if data[i+1] in octdigits:
86 for n in range(2, 5):
87 if data[i+n] not in octdigits:
88 break
89 word = data[i:i+n]
90 i = i + n
91 elif data[i+1] == 'x':
92 for n in range(2, 5):
93 if data[i+n] not in hexdigits:
94 break
95 word = data[i:i+n]
96 i = i + n
97 else:
98 word = data[i:i+2]
99 i = i + 2
100
101 l = len(word)
102 if c + l >= 78-1:
103 fp.write("\\\n")
104 c = 0
105 fp.write(word)
106 c = c + l
107
108 # return the formatted compressed data
109 return fp.getvalue()
110
111
112
113 def main(args):
114 if not args or ("-h" in args):
115 print __doc__
116 return
117
118 append = 0
119 compressed = 1
120 maskClr = None
121 imgName = ""
122 icon = 0
123 catalog = 0
124
125 try:
126 opts, fileArgs = getopt.getopt(args, "auicn:m:")
127 except getopt.GetoptError:
128 print __doc__
129 return
130
131 for opt, val in opts:
132 if opt == "-a":
133 append = 1
134 elif opt == "-u":
135 compressed = 0
136 elif opt == "-n":
137 imgName = val
138 elif opt == "-m":
139 maskClr = val
140 elif opt == "-i":
141 icon = 1
142 elif opt == "-c":
143 catalog = 1
144
145 if len(fileArgs) != 2:
146 print __doc__
147 return
148
149 image_file, python_file = fileArgs
150
151 # convert the image file to a temporary file
152 tfname = tempfile.mktemp()
153 ok, msg = img2img.convert(image_file, maskClr, None, tfname, wx.wxBITMAP_TYPE_PNG, ".png")
154 if not ok:
155 print msg
156 return
157
158 data = open(tfname, "rb").read()
159 data = crunch_data(data, compressed)
160 os.unlink(tfname)
161
162 if append:
163 out = open(python_file, "a")
164 else:
165 out = open(python_file, "w")
166
167 if catalog:
168 pyPath, pyFile = os.path.split(python_file)
169 imgPath, imgFile = os.path.split(image_file)
170
171 if not imgName:
172 imgName = os.path.splitext(imgFile)[0]
173 print "\nWarning: -n not specified. Using filename (%s) for catalog entry." % imgName
174
175 old_index = []
176 if append:
177 # check to see if catalog exists already (file may have been created
178 # with an earlier version of img2py or without -c option)
179 oldSysPath = sys.path[:]
180 sys.path = [pyPath] # make sure we don't import something else by accident
181 mod = __import__(os.path.splitext(pyFile)[0])
182 if 'index' not in dir(mod):
183 print "\nWarning: %s was originally created without catalog." % python_file
184 print " Any images already in file will not be cataloged.\n"
185 out.write("\n# ***************** Catalog starts here *******************")
186 out.write("\n\ncatalog = {}\n")
187 out.write("index = []\n\n")
188 out.write("class ImageClass: pass\n\n")
189 else: # save a copy of the old index so we can warn about duplicate names
190 old_index[:] = mod.index[:]
191 del mod
192 sys.path = oldSysPath[:]
193
194 out.write("#" + "-" * 70 + "\n")
195 if not append:
196 out.write("# This file was generated by %s\n#\n" % sys.argv[0])
197 out.write("from wxPython.wx import wxImageFromStream, wxBitmapFromImage\n")
198 if icon:
199 out.write("from wxPython.wx import wxEmptyIcon\n")
200 if compressed:
201 out.write("import cStringIO, zlib\n\n\n")
202 else:
203 out.write("import cStringIO\n\n\n")
204
205 if catalog:
206 out.write("catalog = {}\n")
207 out.write("index = []\n\n")
208 out.write("class ImageClass: pass\n\n")
209
210 if compressed:
211 out.write("def get%sData():\n"
212 " return zlib.decompress(\n%s)\n\n"
213 % (imgName, data))
214 else:
215 out.write("def get%sData():\n"
216 " return \\\n%s\n\n"
217 % (imgName, data))
218
219
220 out.write("def get%sBitmap():\n"
221 " return wxBitmapFromImage(get%sImage())\n\n"
222 "def get%sImage():\n"
223 " stream = cStringIO.StringIO(get%sData())\n"
224 " return wxImageFromStream(stream)\n\n"
225 % tuple([imgName] * 4))
226 if icon:
227 out.write("def get%sIcon():\n"
228 " icon = wxEmptyIcon()\n"
229 " icon.CopyFromBitmap(get%sBitmap())\n"
230 " return icon\n\n"
231 % tuple([imgName] * 2))
232
233 if catalog:
234 if imgName in old_index:
235 print "Warning: %s already in catalog." % imgName
236 print " Only the last entry will be accessible.\n"
237 old_index.append(imgName)
238 out.write("index.append('%s')\n" % imgName)
239 out.write("catalog['%s'] = ImageClass()\n" % imgName)
240 out.write("catalog['%s'].getData = get%sData\n" % tuple([imgName] * 2))
241 out.write("catalog['%s'].getImage = get%sImage\n" % tuple([imgName] * 2))
242 out.write("catalog['%s'].getBitmap = get%sBitmap\n" % tuple([imgName] * 2))
243 if icon:
244 out.write("catalog['%s'].getIcon = get%sIcon\n" % tuple([imgName] * 2))
245 out.write("\n\n")
246
247 if imgName:
248 n_msg = ' using "%s"' % imgName
249 else:
250 n_msg = ""
251 if maskClr:
252 m_msg = " with mask %s" % maskClr
253 else:
254 m_msg = ""
255 print "Embedded %s%s into %s%s" % (image_file, n_msg, python_file, m_msg)
256
257
258 if __name__ == "__main__":
259 main(sys.argv[1:])
260