img.html


001| '''Images.
001| 
001| classes:
001|     Point       (object)
001|     Img         (object)
001|     Chart       (Img)
001|     XYChart     (Chart)
001| 
001| functions:
001|     dispatch(cmd,[args])    - Module Command Dispatch
001|     doit()                  - Default function
001| 
001| Developer@Sonnack.com
001| May 2012
001| '''

002| ####################################################################################################
003| from sys import argv, stderr
004| from os import path
005| from math import sin,cos, radians
006| from random import seed, random, randint
007| from PIL import Image, ImageDraw, ImageFont
008| from colors import ColorBlack, ColorWhite, ColorBlue, ColorDarkBlue, ColorGreen, ColorRed, ColorYellow
009| from colors import ColorGray, ColorFaintGray, ColorLightGray, ColorDarkGray, ColorGray100, ColorGray200
010| ####################################################################################################
011| Log = stderr
012| 
013| fBox = lambda xy,d: (xy[0]-int(d/2), xy[1]-int(d/2), xy[0]+int(d/2), xy[1]+int(d/2))
014| 
015| tAdd = lambda t1,t2: tuple(map(lambda x1,x2: x1+x2, t1, t2))
016| tSub = lambda t1,t2: tuple(map(lambda x1,x2: x1-x2, t1, t2))
017| 
018| seed()
019| 
020| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
021| class Point (object):
022|     '''Point class.'''
023|     def __init__ (self, x=0, y=0):
024|         '''Create new Point instance.'''
025|         self.x = x
026|         self.y = y
027| 
028|     def __str__ (self):
029|         '''String version (a comma-separated number pair).'''
030|         return '%f, %f' % (self.x, self.y)
031| 
032|     def __repr__ (self):
033|         '''Canonical representation (a tuple).'''
034|         return (self.x, self.y)
035| 
036| 
037| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
038| class PieGraph (object):
039|     def __init__ (self, data):
040|         '''New PieGraph instance.  {data=pie slice sizes}'''
041|         tot = sum([float(x) for x in data])
042|         #print('tot: %s' % tot)
043|         self.pieces = map(lambda x: [x, float(x)/tot, 0,0], data)
044|         a = 0
045|         for pc in self.pieces:
046|             pc[2] = a
047|             a = a + int(pc[1] * 360.0)
048|             pc[3] = a
049| 
050|     def draw (self, img, xy, radius):
051|         '''New PieGraph instance.  {img=Img instance, xy=location tuple}'''
052|         bx = fBox(xy, radius)
053|         #print('box: %s' % bx)
054|         for pc in self.pieces:
055|             c = (randint(0,255),randint(0,255),randint(0,255))
056|             img.draw.pieslice(bx, pc[2],pc[3], fill=c, outline=ColorBlack)
057|             #print(pc)
058|         return self
059| 
060| 
061| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
062| class Img (object):
063|     '''\
063| Image base class.
063| 
063| This simple class just encapsulates the Image API in a helper object.
063| 
063| Note that images created with this class automatically have a three-pixel
063| border around them.
063| 
063| usage:
063|         dims = (640, 480)
063|         im = Img(dims)
063| 
063| '''

064|     def __init__ (self, dims, bg=ColorWhite):
065|         '''Create new Img instance with given dimensions.'''
066|         self.dims = dims
067|         self.im = Image.new('RGB', dims, bg)
068|         self.draw = ImageDraw.Draw(self.im)
069|         self.draw.rectangle((0,0)+(self.dims[0]-1,self.dims[1]-1), outline=ColorBlack)
070|         self.draw.rectangle((1,1)+(self.dims[0]-2,self.dims[1]-2), outline=ColorDarkGray)
071|         self.draw.rectangle((2,2)+(self.dims[0]-3,self.dims[1]-3), outline=ColorGray)
072| 
073|     def get (self, xy):
074|         if not (isinstance(xy,tuple) or isinstance(xy,list)):
075|             raise TypeError('Index must be a tuple or list! (not a "%s")' % type(xy).__name__)
076|         if not (len(xy) == 2):
077|             raise TypeError('Index must have two coordinates! (not %d)' % len(xy))
078|         if (self.dims[0] <= xy[0]) or (self.dims[1] < xy[1]):
079|             raise IndexError('Index out of bounds! %s' % str(xy))
080|         return self.im.getpixel(xy)
081| 
082|     def circle (self, xy, radius, fg, bg):
083|         '''Draw a circle.'''
084|         ulc = (xy[0]-radius, xy[1]-radius)
085|         lrc = (xy[0]+radius, xy[1]+radius)
086|         self.draw.ellipse([ulc, lrc], outline=fg, fill=bg)
087|         return self
088| 
089|     def show (self):
090|         '''Display image in default viewer.'''
091|         self.im.show()
092|         return self
093| 
094|     def save (self, fn, mode='PNG'):
095|         '''Save image as a file.'''
096|         self.im.save(fn, mode)
097|         return self
098| 
099|     def __str__ (self):
100|         '''String version: format, size, mode.'''
101|         s = '%s (%d,%d) %s'
102|         t = (self.im.format, self.im.size[0], self.im.size[1], self.im.mode)
103|         return s % t
104| 
105|     def __repr__ (self):
106|         '''Canonical representation (JSON-like string).'''
107|         s = '{Img:{format:"%s", size:%s, mode:"%s", addr:%x}}'
108|         t = (self.im.format, str(self.im.size), self.im.mode, self.__hash__())
109|         return s % t
110| 
111| 
112| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
113| class Chart (Img):
114|     '''Chart Image base class.
114| 
114| This class encapsulates the idea of a plot area on the image.
114| There is a title centered across the top of the plot area.
114| There is an X-axis along the bottom and a Y-axis along the left.
114| 
114| The values provided for the axes are evenly spaced along the plot area sides.
114| The values may be strings or numbers (which are converted to strings).
114| 
114| Note that the Y-axis text is painted from top-to-bottom, so the first
114| value provided in the list goes at the top and the last on goes at the
114| axis bottom.
114| 
114| Currently the client must call the .make() method to generate the
114| plot area, title and axes. If not called, the chart just has its
114| gray background (making it similar to a plain image).
114| 
114| Clients use the .plot_ulc, .plot_lrc and .plot_dim properties to draw
114| directly on the chart plot area. Each property is a (x,y) tuple. The
114| first two define the corners; the last one defines the plot area size.
114| 
114| usage:
114|         ttl = 'My Awesome Chart'
114|         sz  = (640, 480)
114|         xa  = [0, 90, 180, 270, 360]
114|         ya  = [+1, 0, -1]
114|         im = Img(sz, ttl, xa,ya)
114|         im.make()
114| 
114| '''

115|     def __init__ (self, dims, title=None, x_axis=[], y_axis=[], bg=ColorWhite):
116|         '''Create new Chart instance.'''
117|         super(Chart,self).__init__(dims, ColorFaintGray)
118|         self.font_axis = ImageFont.truetype('arial.ttf', size=10)
119|         self.font_title = ImageFont.truetype('arialbd.ttf', size=14)
120|         self.margin = (9,4,12,9)
121|         self.title = title
122|         self.x_axis = x_axis
123|         self.y_axis = y_axis
124|         self.plot_bg = bg
125|         # Title box...
126|         self.title_box = self.draw.textsize(self.title, font=self.font_title) if self.title else (0,0)
127|         # X-axis box...
128|         self.x_axis_box = self._calc_axis_text_size(self.x_axis)
129|         # Y-axis box...
130|         self.y_axis_box = self._calc_axis_text_size(self.y_axis)
131|         # Plot box...
132|         self.plot_ulc = (self.margin[0] + self.y_axis_box[0], self.margin[1] + self.title_box[1] + 3)
133|         self.plot_lrc = (dims[0]-self.margin[2], dims[1]-(self.margin[3] + self.x_axis_box[1]))
134|         self.plot_dim = tSub(self.plot_lrc, self.plot_ulc)
135|         #
136|         self.x_axis_ulc = (self.plot_ulc[0], self.plot_lrc[1])
137|         self.x_axis_box = (self.plot_dim[0], self.x_axis_box[1])
138|         #
139|         self.y_axis_ulc = (self.margin[0]    , self.plot_ulc[1])
140|         self.y_axis_box = (self.y_axis_box[0], self.plot_dim[1])
141|         #
142|         self.title_ulc = (self.plot_ulc[0] + (int(self.plot_dim[0] / 2) - int(self.title_box[0] / 2)), self.margin[1])
143|         #print("plot: %s, %s" % (self.plot_ulc, self.plot_lrc))
144| 
145|     def make (self):
146|         '''Make the chart.'''
147|         self._draw_plot_area()
148|         self._draw_x_axis()
149|         self._draw_y_axis()
150|         if self.title:
151|             self.draw.text(self.title_ulc, self.title, font=self.font_title, fill=ColorBlack)
152|         return self
153| 
154|     def _draw_plot_area (self):
155|         '''private:Draw Plot Area.'''
156|         self.draw.rectangle([self.plot_ulc, self.plot_lrc], outline=ColorBlack, fill=self.plot_bg)
157|         return self
158| 
159|     def _draw_x_axis (self):
160|         '''private:Draw X-Axis.'''
161|         if not self.x_axis:
162|             return self
163|         lrc = tAdd(self.x_axis_ulc, self.x_axis_box)
164|         n = len(self.x_axis)
165|         px = int(self.x_axis_box[0] / (n-1)) if 1 < n else 0
166|         for ix,t in enumerate(self.x_axis):
167|             s = str(t)
168|             sz = self.draw.textsize(s, font=self.font_axis)
169|             if ix == 0:
170|                 # First one left justifies...
171|                 ulc = self.x_axis_ulc
172|             elif ix == (n - 1):
173|                 # Last one right justifies...
174|                 ulc = tSub(lrc, sz)
175|             else:
176|                 # Others center...
177|                 ulc = ((self.x_axis_ulc[0] + (ix * px)) - int(sz[0]/2), self.x_axis_ulc[1])
178|             self.draw.text(ulc, s, font=self.font_axis, fill=ColorBlack)
179|         return self
180| 
181|     def _draw_y_axis (self):
182|         '''private:Draw Y-Axis.'''
183|         if not self.y_axis:
184|             return self
185|         lrc = tAdd(self.y_axis_ulc, self.y_axis_box)
186|         n = len(self.y_axis)
187|         py = int(self.y_axis_box[1] / (n-1)) if 1 < n else 0
188|         for ix,t in enumerate(self.y_axis):
189|             s = str(t)
190|             sz = self.draw.textsize(s, font=self.font_axis)
191|             if ix == 0:
192|                 # First one top justifies...
193|                 ulc = (lrc[0]-sz[0], self.y_axis_ulc[1])
194|             elif ix == (n - 1):
195|                 # Last one bottom justifies...
196|                 ulc = tSub(lrc, sz)
197|             else:
198|                 # Others center...
199|                 ulc = (lrc[0]-sz[0], (self.y_axis_ulc[1] + (ix * py)) - int(sz[1]/2))
200|             self.draw.text(ulc, s, font=self.font_axis, fill=ColorBlack)
201|         return self
202| 
203|     def _calc_axis_text_size (self, axis):
204|         '''private:Calculate Axis Text Size.'''
205|         rv = [0,0]
206|         for t in axis:
207|             s = str(t)
208|             sz = self.draw.textsize(s, font=self.font_axis)
209|             if rv[0] < sz[0]:
210|                 rv[0] = sz[0]
211|             if rv[1] < sz[1]:
212|                 rv[1] = sz[1]
213|         return tuple(rv)
214| 
215|     def __repr__ (self):
216|         '''Canonical representation (JSON-like string).'''
217|         s = '{Chart:{parent:%s, ulc:%s, lrc:%s, plot:%s, title:"%s"}}'
218|         t = (super(Chart,self).__repr__(), str(self.plot_ulc), str(self.plot_lrc), str(self.plot_dim), self.title)
219|         return s % t
220| 
221| 
222| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
223| class XYChart (Chart):
224|     '''\
224| XY Chart Image class.
224| 
224| This class adds the capability to draw in the plot area.
224| 
224| usage:
224|         ttl = 'My Awesome Chart'
224|         sz  = (640, 480)
224|         pz  = (360, 2)
224|         xa  = [0, 90, 180, 270, 360]
224|         ya  = [+1, 0, -1]
224|         xg  = (90, 30)
224|         yg  = (1, )
224|         im = XYChart(sz, ttl, xa,ya, xg,yg)
224|         im.make()
224| 
224| '''

225|     def __init__ (self, dims, scale, title=None, x_axis=[], y_axis=[], x_grid=(), y_grid=(), bg=ColorWhite):
226|         '''Create new Chart. {dims=(x,y), scale=(x,y), _axis=[], _grid=(max,min)}'''
227|         super(XYChart,self).__init__(dims, title, x_axis, y_axis, bg)
228|         self.scale = scale
229|         self.x_grid = x_grid
230|         self.y_grid = y_grid
231|         #
232|         self.factor = (self.plot_dim[0] / float(self.scale[0]), self.plot_dim[1] / float(self.scale[1]))
233|         #print("factor: %s" % self.factor)
234| 
235|     def make (self):
236|         '''Make the Chart.'''
237|         super(XYChart,self).make()
238|         self._draw_x_grid()
239|         self._draw_y_grid()
240|         return self
241| 
242|     def plot (self, data, color=ColorRed, width=1):
243|         '''Draw the Chart. {data=[xy1,xy2,..]}'''
244|         pdata = [(self.fx(t[0]), self.fy(t[1])) for t in data]
245|         self.draw.line(pdata, fill=color, width=width)
246|         return self
247| 
248|     def plot_vlines (self, data, color=ColorRed, width=1):
249|         '''Draw the Chart using vertical lines.'''
250|         yb = self.fy(0)
251|         pdata = [(self.fx(t[0]), self.fy(t[1])) for t in data]
252|         for pt in pdata:
253|             self.draw.line([(pt[0],yb), pt], fill=color, width=width)
254| 
255|     def fx (self, x):
256|         '''Factor X.'''
257|         return self.plot_ulc[0] + (x * self.factor[0])
258| 
259|     def fy (self, y):
260|         '''Factor Y.'''
261|         return self.plot_lrc[1] - (y * self.factor[1])
262| 
263|     def _draw_x_grid (self):
264|         '''private:Draw X Grid.'''
265|         if not self.x_grid:
266|             return self
267|         if 1 < len(self.x_grid):
268|             x = self.x_grid[1]
269|             while x < self.scale[0]:
270|                 px = self.fx(x)
271|                 p0 = (px, self.plot_ulc[1]+1)
272|                 p1 = (px, self.plot_lrc[1]-1)
273|                 self.draw.line([p0, p1], fill=ColorGray200)
274|                 x = x + self.x_grid[1]
275|         if 0 < len(self.x_grid):
276|             x = self.x_grid[0]
277|             while x < self.scale[0]:
278|                 px = self.fx(x)
279|                 p0 = (px, self.plot_ulc[1]+1)
280|                 p1 = (px, self.plot_lrc[1]-1)
281|                 self.draw.line([p0, p1], fill=ColorGray100)
282|                 x = x + self.x_grid[0]
283|         return self
284| 
285|     def _draw_y_grid (self):
286|         '''private:Draw Y Grid.'''
287|         if not self.y_grid:
288|             return self
289|         if 1 < len(self.y_grid):
290|             y = self.y_grid[1]
291|             while y < self.scale[1]:
292|                 py = self.fy(y)
293|                 p0 = (self.plot_ulc[0]+1, py)
294|                 p1 = (self.plot_lrc[0]-1, py)
295|                 self.draw.line([p0, p1], fill=ColorGray200)
296|                 y = y + self.y_grid[1]
297|         if 0 < len(self.y_grid):
298|             y = self.y_grid[0]
299|             while y < self.scale[1]:
300|                 py = self.fy(y)
301|                 p0 = (self.plot_ulc[0]+1, py)
302|                 p1 = (self.plot_lrc[0]-1, py)
303|                 self.draw.line([p0, p1], fill=ColorGray100)
304|                 y = y + self.y_grid[0]
305|         return self
306| 
307|     def __repr__ (self):
308|         '''Canonical representation (JSON-like string).'''
309|         s = '{XYChart:{parent:%s, scale:%s, xgrid:%s, ygrid:%s}}'
310|         t = (super(XYChart,self).__repr__(), str(self.scale), str(self.x_grid), str(self.y_grid))
311|         return s % t
312| 
313| 
314| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
315| class BarChart (Chart):
316|     '''Bar Chart Image class.'''
317|     def __init__ (self, dims, y_scale, title=None, x_axis=[], y_axis=[], y_grid=(), bg=ColorWhite):
318|         '''Create new Chart. {dims=(x,y), _axis=[], y_scale=f, y_grid=(max,min)}'''
319|         super(BarChart,self).__init__(dims, title, x_axis, y_axis, bg)
320|         self.y_scale = y_scale
321|         self.y_grid = y_grid
322|         self.y_factor = float(self.plot_dim[1]) / float(y_scale)
323|         #print("factor: %s" % self.y_factor)
324| 
325|     def make (self):
326|         super(BarChart,self).make()
327|         self._draw_y_grid()
328|         return self
329| 
330|     def fy (self, y):
331|         return self.plot_lrc[1] - (y * self.y_factor)
332| 
333|     def _draw_y_grid (self):
334|         if not self.y_grid:
335|             return self
336|         if 1 < len(self.y_grid):
337|             for y in range(self.y_grid[1], self.y_scale, self.y_grid[1]):
338|                 py = self.fy(y)
339|                 p0 = (self.plot_ulc[0]+1, py)
340|                 p1 = (self.plot_lrc[0]-1, py)
341|                 self.draw.line([p0, p1], fill=(239,239,239))
342|         if 0 < len(self.y_grid):
343|             for y in range(self.y_grid[0], self.y_scale, self.y_grid[0]):
344|                 py = self.fy(y)
345|                 p0 = (self.plot_ulc[0]+1, py)
346|                 p1 = (self.plot_lrc[0]-1, py)
347|                 self.draw.line([p0, p1], fill=(191,191,191))
348|         return self
349| 
350|     def __repr__ (self):
351|         s = '{BarChart:{parent:%s, ygrid:%s}}'
352|         t = (super(BarChart,self).__repr__(), str(self.y_grid))
353|         return s % t
354| 
355| 
356| ##================================================================================================##
357| def demo0 ():
358|     sz = (640, 480)
359|     pz = (360, 20)
360|     xa = [0, 90, 180, 270, 360]
361|     ya = ['+1', 0, '-1']
362|     xg = (45, )
363|     yg = (5, 1)
364|     im = XYChart(sz, pz, 'Sine and Cosine', xa,ya, xg,yg)
365| 
366|     im.make()
367| 
368|     dda = [(x, 10 + (9 * sin(radians(float(x))))) for x in range(0,360,5)]
369|     ddb = [(x, 10 + (9 * cos(radians(float(x))))) for x in range(0,360,5)]
370| 
371|     im.plot(dda, ColorRed)
372|     im.plot(ddb, ColorBlue)
373| 
374|     # Save & Show...
375|     im.save('demo0.png')
376|     im.show()
377|     return 'Done'
378| 
379| ##================================================================================================##
380| def demo1 ():
381|     IconPath = r'C:\CJS\www\root\app\bb\icons'
382|     fn = 'demo1.png'
383|     sz = (640, 480)
384|     c1 = ( 30,  30)
385|     c2 = (610,  30)
386|     c3 = (610, 450)
387|     c4 = ( 30, 450)
388|     bx = (100, 100, sz[0]-100, sz[1]-100)
389| 
390|     font1 = ImageFont.truetype('arialbd.ttf', size=8)
391|     font2 = ImageFont.truetype('arialbd.ttf', size=10)
392| 
393|     im = Image.new('RGB', sz, ColorWhite)
394|     draw = ImageDraw.Draw(im)
395|     try:
396|         # Draw grid...
397|         c = (223, 223, 255)
398|         for x in range(0, sz[0], 12):
399|             draw.line([(x,0), (x,sz[1]-1)], fill=c)
400|         for y in range(0, sz[1], 12):
401|             draw.line([(0,y), (sz[0]-1,y)], fill=c)
402| 
403|         # Draw corner circles...
404|         draw.ellipse(fBox(c1,40), fill=ColorRed   , outline=ColorBlack)
405|         draw.ellipse(fBox(c2,40), fill=ColorYellow, outline=ColorBlack)
406|         draw.ellipse(fBox(c3,40), fill=ColorGreen , outline=ColorBlack)
407|         draw.ellipse(fBox(c4,40), fill=ColorBlue  , outline=ColorBlack)
408| 
409|         # Draw "plot" area...
410|         draw.rectangle(bx, fill=ColorLightGray, outline=ColorBlack)
411| 
412|         draw.text((bx[0]+29,bx[1]+3), 'American League', font=font2, fill=(0,0,0))
413|         draw.text((bx[0]+225,bx[1]+3), 'National League', font=font2, fill=(0,0,0))
414| 
415|         draw.text((bx[0]+17,bx[1]+20), 'West', font=font1, fill=(0,0,0))
416|         draw.text((bx[0]+65,bx[1]+20), 'Central', font=font1, fill=(0,0,0))
417|         draw.text((bx[0]+128,bx[1]+20), 'East', font=font1, fill=(0,0,0))
418| 
419|         draw.text((bx[0]+213,bx[1]+20), 'West', font=font1, fill=(0,0,0))
420|         draw.text((bx[0]+261,bx[1]+20), 'Central', font=font1, fill=(0,0,0))
421|         draw.text((bx[0]+324,bx[1]+20), 'East', font=font1, fill=(0,0,0))
422| 
423|         # AL - West
424|         x = bx[0] + 12
425|         y = bx[1] + 36
426|         icon = Image.open(path.join(IconPath,'im_logo_sea_36x32.png'))
427|         im.paste(icon, (x,y))
428|         y = y + icon.size[1]
429|         icon = Image.open(path.join(IconPath,'im_logo_oak_36x32.png'))
430|         im.paste(icon, (x,y))
431|         y = y + icon.size[1]
432|         icon = Image.open(path.join(IconPath,'im_logo_ana_36x32.png'))
433|         im.paste(icon, (x,y))
434|         y = y + icon.size[1]
435|         icon = Image.open(path.join(IconPath,'im_logo_tex_36x32.png'))
436|         im.paste(icon, (x,y))
437|         y = y + icon.size[1]
438|         icon = Image.open(path.join(IconPath,'im_logo_hou_36x32.png'))
439|         im.paste(icon, (x,y))
440| 
441|         # AL - Central
442|         x = x + int(icon.size[0] * 1.5)
443|         y = bx[1] + 36
444|         icon = Image.open(path.join(IconPath,'im_logo_min_36x32.png'))
445|         im.paste(icon, (x,y))
446|         y = y + icon.size[1]
447|         icon = Image.open(path.join(IconPath,'im_logo_cha_36x32.png'))
448|         im.paste(icon, (x,y))
449|         y = y + icon.size[1]
450|         icon = Image.open(path.join(IconPath,'im_logo_det_36x32.png'))
451|         im.paste(icon, (x,y))
452|         y = y + icon.size[1]
453|         icon = Image.open(path.join(IconPath,'im_logo_cle_36x32.png'))
454|         im.paste(icon, (x,y))
455|         y = y + icon.size[1]
456|         icon = Image.open(path.join(IconPath,'im_logo_kca_36x32.png'))
457|         im.paste(icon, (x,y))
458| 
459|         # AL - East
460|         x = x + int(icon.size[0] * 1.5)
461|         y = bx[1] + 36
462|         icon = Image.open(path.join(IconPath,'im_logo_tor_36x32.png'))
463|         im.paste(icon, (x,y))
464|         y = y + icon.size[1]
465|         icon = Image.open(path.join(IconPath,'im_logo_bos_36x32.png'))
466|         im.paste(icon, (x,y))
467|         y = y + icon.size[1]
468|         icon = Image.open(path.join(IconPath,'im_logo_nya_36x32.png'))
469|         im.paste(icon, (x,y))
470|         y = y + icon.size[1]
471|         icon = Image.open(path.join(IconPath,'im_logo_bal_36x32.png'))
472|         im.paste(icon, (x,y))
473|         y = y + icon.size[1]
474|         icon = Image.open(path.join(IconPath,'im_logo_tba_36x32.png'))
475|         im.paste(icon, (x,y))
476| 
477|         # NL - West
478|         x = x + int(icon.size[0] * 2.5)
479|         y = bx[1] + 36
480|         icon = Image.open(path.join(IconPath,'im_logo_sfn_36x32.png'))
481|         im.paste(icon, (x,y))
482|         y = y + icon.size[1]
483|         icon = Image.open(path.join(IconPath,'im_logo_lan_36x32.png'))
484|         im.paste(icon, (x,y))
485|         y = y + icon.size[1]
486|         icon = Image.open(path.join(IconPath,'im_logo_sdn_36x32.png'))
487|         im.paste(icon, (x,y))
488|         y = y + icon.size[1]
489|         icon = Image.open(path.join(IconPath,'im_logo_ari_36x32.png'))
490|         im.paste(icon, (x,y))
491|         y = y + icon.size[1]
492|         icon = Image.open(path.join(IconPath,'im_logo_col_36x32.png'))
493|         im.paste(icon, (x,y))
494| 
495|         # NL - Central
496|         x = x + int(icon.size[0] * 1.5)
497|         y = bx[1] + 36
498|         icon = Image.open(path.join(IconPath,'im_logo_mil_36x32.png'))
499|         im.paste(icon, (x,y))
500|         y = y + icon.size[1]
501|         icon = Image.open(path.join(IconPath,'im_logo_chn_36x32.png'))
502|         im.paste(icon, (x,y))
503|         y = y + icon.size[1]
504|         icon = Image.open(path.join(IconPath,'im_logo_pit_36x32.png'))
505|         im.paste(icon, (x,y))
506|         y = y + icon.size[1]
507|         icon = Image.open(path.join(IconPath,'im_logo_cin_36x32.png'))
508|         im.paste(icon, (x,y))
509|         y = y + icon.size[1]
510|         icon = Image.open(path.join(IconPath,'im_logo_sln_36x32.png'))
511|         im.paste(icon, (x,y))
512| 
513|         # NL - East
514|         x = x + int(icon.size[0] * 1.5)
515|         y = bx[1] + 36
516|         icon = Image.open(path.join(IconPath,'im_logo_nyn_36x32.png'))
517|         im.paste(icon, (x,y))
518|         y = y + icon.size[1]
519|         icon = Image.open(path.join(IconPath,'im_logo_phi_36x32.png'))
520|         im.paste(icon, (x,y))
521|         y = y + icon.size[1]
522|         icon = Image.open(path.join(IconPath,'im_logo_was_36x32.png'))
523|         im.paste(icon, (x,y))
524|         y = y + icon.size[1]
525|         icon = Image.open(path.join(IconPath,'im_logo_atl_36x32.png'))
526|         im.paste(icon, (x,y))
527|         y = y + icon.size[1]
528|         icon = Image.open(path.join(IconPath,'im_logo_mia_36x32.png'))
529|         im.paste(icon, (x,y))
530| 
531|         draw.arc(fBox((sz[0]-1, sz[1]-1), 12), 190,260, fill=ColorDarkBlue)
532|         draw.arc(fBox((sz[0]-1, sz[1]-1), 15), 190,260, fill=ColorDarkBlue)
533|         draw.arc(fBox((sz[0]-1, sz[1]-1), 19), 190,260, fill=ColorDarkBlue)
534|         draw.arc(fBox((sz[0]-1, sz[1]-1), 24), 190,260, fill=ColorDarkBlue)
535| 
536|         draw.rectangle((0,0, sz[0]-1,sz[1]-1), outline=ColorBlack)
537|         draw.rectangle((1,1, sz[0]-2,sz[1]-2), outline=ColorDarkGray)
538|         draw.rectangle((2,2, sz[0]-3,sz[1]-3), outline=ColorGray)
539|         draw.rectangle((3,3, sz[0]-4,sz[1]-4), outline=ColorLightGray)
540| 
541|         s = 'Chris@Sonnack.com'
542|         b = draw.textsize(s, font=font1)
543|         x = sz[0] - (b[0]+50)
544|         y = sz[1] - (b[1]+5)
545|         draw.text((x,y), s, font=font1, fill=(127,127,127))
546| 
547|     except Exception as e:
548|         print(e, file=stderr)
549|         return e
550|     finally:
551|         del draw
552|         im.save(fn, 'PNG')
553| 
554|     im.show()
555|     return 'Done'
556| 
557| ##================================================================================================##
558| def demo2 ():
559|     ChartMax  = (164, 120)
560|     ChartMul  = (2, 1)
561|     ChartSize = (ChartMax[0] * ChartMul[0], (1 + (2 * ChartMax[1])) * ChartMul[1])
562|     ChartDims = (ChartSize[0]+30, ChartSize[1]+30)
563|     ChartULC  = (20, 10)
564|     ChartLRC  = (ChartULC[0]+ChartSize[0], ChartULC[1]+ChartSize[1])
565|     ChartX    = lambda x: ChartULC[0] + (2 * int(x))
566|     ChartY    = lambda y: (ChartULC[1] + ChartMax[1]) - int(y)
567| 
568|     fn = 'demo2.png'
569|     x0 = ChartX(1)
570|     x1 = ChartX(ChartMax[0]-1)
571|     zy = ChartY(0)
572| 
573|     im = Image.new('RGB', ChartDims, ColorWhite)
574|     draw = ImageDraw.Draw(im)
575|     try:
576|         # Draw border...
577|         draw.rectangle((0,0)+(ChartDims[0]-1,ChartDims[1]-1), outline=ColorBlack)
578|         draw.rectangle((2,2)+(ChartDims[0]-3,ChartDims[1]-3), outline=ColorDarkGray)
579| 
580|         # Draw plot area...
581|         draw.rectangle(ChartULC+ChartLRC, fill=ColorLightGray, outline=ColorBlack)
582| 
583|         m = int(20)
584|         f = ChartMax[1] / float(m)
585| 
586|         # Draw grid lines...
587|         for n in range(1, m):
588|             yp = ChartY(f * +n)
589|             yn = ChartY(f * -n)
590|             c = ColorGray if n % 10 else ColorDarkGray
591|             draw.line([(x0,yp), (x1,yp)], width=1, fill=c)
592|             draw.line([(x0,yn), (x1,yn)], width=1, fill=c)
593| 
594|         # Draw Y-Zero Axis...
595|         draw.line([(x0,zy), (x1,zy)], width=1, fill=ColorBlack)
596| 
597|         # Draw test pattern (sine wave)...
598|         for x in range(ChartMax[0]-1):
599|             px = ChartX(1+x)
600|             py = ChartY(int(80 * sin(radians((x/float(ChartMax[0])) * 360.0))))
601|             draw.point((px, py), fill=ColorRed)
602| 
603|     except Exception as e:
604|         print(e, file=stderr)
605|         return e
606|     finally:
607|         del draw
608|         im.save(fn, 'PNG')
609| 
610|     im.show()
611|     return 'Done'
612| 
613| ##================================================================================================##
614| def demo3 ():
615|     class GameCounter (object):
616|         def __init__ (self):
617|             self.games = 0
618|         def get (self):
619|             if random() < 0.5:
620|                 self.games = self.games + 1
621|             return self.games
622| 
623|     fn = 'demo3.png'
624|     sz = (640, 480)
625|     pz = (162, 100)
626|     xa = [0, 27, 54, 81, 108, 135, 162]
627|     ya = [100, 75, 50, 25, 0]
628|     xg = (27, 3)
629|     yg = (25, 5)
630|     im = XYChart(sz, pz, 'Twins Team BA - 2013', xa,ya, xg,yg)
631| 
632|     im.make()
633| 
634|     gc = GameCounter()
635|     dd = [(0,0)] + [(1+x, gc.get()) for x in range(81)]
636|     im.plot(dd, ColorRed)
637| 
638|     gc = GameCounter()
639|     dd = [(0,0)] + [(1+x, gc.get()) for x in range(162)]
640|     im.plot(dd, ColorBlue)
641| 
642|     gc = GameCounter()
643|     dd = [(0,0)] + [(1+x, gc.get()) for x in range(162)]
644|     im.plot(dd, (0,127,0))
645| 
646|     # Save & Show...
647|     im.save(fn)
648|     im.show()
649|     return 'Done'
650| 
651| ##================================================================================================##
652| def demo4 ():
653|     sz = (640, 480)
654|     pz = (100, 100)
655|     xa = [0.0, .25, .50, .75, 1.0]
656|     ya = ['1.0', .50, '0.0']
657|     xg = (25, 5)
658|     yg = (25, 5)
659|     F = lambda x: 100 * ((float(100-x)/100.0) ** 2)
660| 
661|     dda = [(x, F(x)) for x in range(100)]
662| 
663|     im = XYChart(sz, pz, 'Curve', xa,ya, xg,yg)
664|     im.make()
665|     im.plot(dda, ColorRed)
666|     # Save & Show...
667|     im.save('demo4.png')
668|     im.show()
669|     return 'Done'
670| 
671| ##================================================================================================##
672| def dispatch (cmd, *args):
673|     print('command: %s' % cmd)
674|     print('#-args: %d' % len(args))
675|     if cmd == 'demo0': return demo0()
676|     if cmd == 'demo1': return demo1()
677|     if cmd == 'demo2': return demo2()
678|     if cmd == 'demo3': return demo3()
679|     if cmd == 'demo4': return demo4()
680|     return 'Nothing to do!'
681| 
682| ####################################################################################################
683| if __name__ == '__main__':
684|     print('autorun: %s' % argv[0])
685|     cmnd = argv[1] if 1 < len(argv) else 'demo1'
686|     args = argv[2:] if 2 < len(argv) else []
687|     obj = dispatch(cmnd, *args)
688|     print(obj)
689| ####################################################################################################
690| '''eof'''
691|