Code

standardize indents on 4 spaces
[inkscape.git] / share / extensions / embedimage.py
1 #!/usr/bin/env python 
2 '''
3 Copyright (C) 2005 Aaron Spike, aaron@ekips.org
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 '''
20 import inkex, os, base64
22 class MyEffect(inkex.Effect):
23     def __init__(self):
24         inkex.Effect.__init__(self)
26     def effect(self):
27         ctx = inkex.xml.xpath.Context.Context(self.document,processorNss=inkex.NSS)
28         
29         # if there is a selection only embed selected images
30         # otherwise embed all images
31         if (self.options.ids):
32             for id, node in self.selected.iteritems():
33                 if node.tagName == 'image':
34                     self.embedImage(node)
35         else:
36             path = '//image'
37             for node in inkex.xml.xpath.Evaluate(path,self.document, context=ctx):
38                 self.embedImage(node)
39     def embedImage(self, node):
40         xlink = node.attributes.getNamedItemNS(inkex.NSS[u'xlink'],'href')
41         if (xlink.value[:4]!='data'):
42             absref=node.attributes.getNamedItemNS(inkex.NSS[u'sodipodi'],'absref')
43             if (os.path.isfile(absref.value)):
44                 file = open(absref.value,"rb").read()
45                 embed=True
46                 if (file[:4]=='\x89PNG'):
47                     type='image/png'
48                 elif (file[:2]=='\xff\xd8'):
49                     type='image/jpg'
50                 else:
51                     embed=False
52                 if (embed):
53                     xlink.value = 'data:%s;base64,%s' % (type, base64.encodestring(file))
54                     node.removeAttributeNS(inkex.NSS[u'sodipodi'],'absref')
55                 else:
56                     inkex.debug("%s is not of type image/png or image/jpg" % absref.value)
57             else:
58                 inkex.debug("Sorry we could not locate %s" % absref.value)
59 e = MyEffect()
60 e.affect()