image: improve image handling, caption, resize
[treecutter.git] / xinclude / pic.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 from dateutil.tz import *
5 from datetime import datetime
6 from dateutil.parser import parse
7
8 import os
9 import sys
10 import Image
11
12 from lxml import etree
13 from lxml.builder import ElementMaker
14
15 from treecutter import constants as const
16
17 class Pic(object):
18     def __init__(self, picture, caption):
19         self.picture = picture
20         self.caption = caption
21         self.sizes = [(500,500),(800,800),(1024,1024)]
22         self.outfiles = []
23
24     def thumbnails(self):
25         infile = os.path.splitext(self.picture)
26         for size in self.sizes:
27             outfile = infile[0]+"-"+str(size[0])+infile[1]
28             if infile != outfile:
29                 try:
30                     im = Image.open(self.picture)
31                     im.thumbnail(size, Image.ANTIALIAS)
32                     im.save(outfile, im.format)
33                     self.outfiles.append(outfile)
34                 except IOError:
35                     print "cannot create thumbnail for '%s'" % infile
36         self.outfiles.append(self.picture)
37
38     def db_xml(self):
39         webpic = self.outfiles[0]
40         imw = Image.open(webpic)
41         ww,dw = imw.size
42
43         db = ElementMaker(namespace=const.DB_NS, nsmap=const.NSMAP)
44
45         pics = db.para()
46         for f in self.outfiles:
47             im = Image.open(f)
48             w,d = im.size
49             pics.append(db.link(str(w)+"x"+str(d)+" ",**{const.XLINK+"href": f}))
50         #pics = list(', '.join(pics))
51         #pics.append(')')
52         #        pics.insert(0,'Sizes (')
53         lst = db.mediaobject(
54             db.imageobject(
55                 db.imagedata(fileref=webpic, width=str(ww), depth=str(dw))),
56             db.caption(db.para(self.caption),pics))
57         return lst
58
59 if __name__ == "__main__":
60     for arg in sys.argv[1:]:
61         al = arg.split("=")
62         if al[0] == "lang":
63             lang = al[1]
64         if al[0] == "xptr":
65             argument = al[1]
66     p,c = argument.split("|")
67     pic = Pic(p,c)
68     pic.thumbnails()
69     pxml = pic.db_xml()
70     sys.stdout.write(etree.tostring(pxml,encoding='UTF-8',pretty_print=False))