embedimage.py 4.52 KB
Newer Older
1
#!/usr/bin/env python 
2
'''
3
Copyright (C) 2005,2007 Aaron Spike, aaron@ekips.org
4 5 6 7 8 9 10 11 12 13 14 15 16

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
17
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
'''
19 20 21 22
# standard library
import base64
import os
import sys
23 24 25 26 27 28 29
if sys.version_info[0] < 3:
    import urllib
    import urlparse
else:
    import urllib.request as urllib
    import urllib.parse as urlparse

30 31
# local library
import inkex
32

33

34
class Embedder(inkex.Effect):
35 36
    def __init__(self):
        inkex.Effect.__init__(self)
37 38 39 40
        self.OptionParser.add_option("-s", "--selectedonly",
            action="store", type="inkbool", 
            dest="selectedonly", default=False,
            help="embed only selected images")
41

42
    def effect(self):
43 44 45
        # if slectedonly is enabled and there is a selection only embed selected
        # images. otherwise embed all images
        if (self.options.selectedonly):
46
            self.embedSelected(self.document, self.selected)
47
        else:
48 49 50 51 52 53
            self.embedAll(self.document)

    def embedSelected(self, document, selected):
        self.document=document
        self.selected=selected
        if (self.options.ids):
Thomas Holder's avatar
Thomas Holder committed
54
            for id, node in selected.items():
55
                if node.tag == inkex.addNS('image','svg'):
56 57 58 59
                    self.embedImage(node)

    def embedAll(self, document):
        self.document=document #not that nice... oh well
60
        path = '//svg:image'
61
        for node in self.document.getroot().xpath(path, namespaces=inkex.NSS):
62 63
            self.embedImage(node)

64
    def embedImage(self, node):
65
        xlink = node.get(inkex.addNS('href','xlink'))
66
        if xlink is None or xlink[:5] != 'data:':
67
            absref=node.get(inkex.addNS('absref','sodipodi'))
68
            url=urlparse.urlparse(xlink)
69 70
            href=urllib.url2pathname(url.path)
            
71 72
            path=''
            #path selection strategy:
73
            # 1. href if absolute
74 75
            # 2. realpath-ified href
            # 3. absref, only if the above does not point to a file
76
            if (href != None):
77
                path=os.path.realpath(href)
78 79
            if (not os.path.isfile(path)):
                if (absref != None):
80
                    path=absref
81

Thomas Holder's avatar
Thomas Holder committed
82 83
            if isinstance(path, bytes):
                path = path.decode("utf-8")
84
                
85
            if (not os.path.isfile(path)):
86
                inkex.errormsg(_('No xlink:href or sodipodi:absref attributes found, or they do not point to an existing file! Unable to embed image.'))
87
                if path:
88
                    inkex.errormsg(_("Sorry we could not locate %s") % str(path))
89

90 91
            if (os.path.isfile(path)):
                file = open(path,"rb").read()
92 93 94 95
                embed=True
                if (file[:4]=='\x89PNG'):
                    type='image/png'
                elif (file[:2]=='\xff\xd8'):
96 97 98 99 100
                    type='image/jpeg'
                elif (file[:2]=='BM'):
                    type='image/bmp'
                elif (file[:6]=='GIF87a' or file[:6]=='GIF89a'):
                    type='image/gif'
101 102
                elif (file[:4]=='MM\x00\x2a' or file[:4]=='II\x2a\x00'):
                    type='image/tiff'
103
                #ico files lack any magic... therefore we check the filename instead
104
                elif(path.endswith('.ico')):
105
                    type='image/x-icon' #official IANA registered MIME is 'image/vnd.microsoft.icon' tho
106 107 108
                else:
                    embed=False
                if (embed):
109
                    node.set(inkex.addNS('href','xlink'), 'data:%s;base64,%s' % (type, base64.encodestring(file)))
110 111
                    if (absref != None):
                        del node.attrib[inkex.addNS('absref',u'sodipodi')]
112
                else:
113
                    inkex.errormsg(_("%s is not of type image/png, image/jpeg, image/bmp, image/gif, image/tiff, or image/x-icon") % path)
114 115 116 117

if __name__ == '__main__':
    e = Embedder()
    e.affect()
118 119


120
# vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 fileencoding=utf-8 textwidth=99