-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimg2base64.py
225 lines (185 loc) · 7.35 KB
/
img2base64.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""HTML Image handling for embedded images in markdown cells."""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from ipython_genutils.py3compat import PY3
if PY3:
from html.parser import HTMLParser
else:
from HTMLParser import HTMLParser
import base64
import os.path
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
__all__ = ['img2base64']
def img2base64(s):
"""Parse HTML image references in Markdown cells.
This looks for HTML tags having a img tag name `img`
and converts the image to a data URI for static embedding.
The tranformation looks like this:
`<img src="./Images/My_image.png" width="800" height="800" alt="Alt_name" title="Mytitle" align="center" />`
Becomes
`<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." width="800" height="800" alt="Alt_name" title="Mytitle" align="center" />`
The conversion preserves all other image tag values.
"""
parser = Img2Base64Parser()
parser.feed(s)
parser.close()
outtext = u''
startpos = 0
for img in parser.imglist:
outtext += s[startpos:img[1][0]]
if img[0][1] == 'svg':
outtext += "data:image/%s+xml;base64,%s"% \
(img[0][1],str(img[0][0]).lstrip('b\'').rstrip('\''))
elif img[0][1] == 'pdf':
outtext += "data:application/%s;base64,%s"% \
(img[0][1],str(img[0][0]).lstrip('b\'').rstrip('\''))
else:
outtext += "data:image/%s;base64,%s"% \
(img[0][1],str(img[0][0]).lstrip('b\'').rstrip('\''))
startpos = img[1][1] if len(img)==3 else -1
outtext += s[startpos:] if startpos != -1 else ''
return outtext
#TODO
# def html_img_to_md_img(s):
# """Parse HTML image references in Markdown cells and output latex format.
# This looks for HTML tags having a img tag name `img`
# and any attributes in the list [width, height, alt, src, title].
# This function won't attempt to handle sizes specified in percentages
# because Markdown does not:
# `<img src="./Images/My_image.png" width="800" height="800" alt="Alt_name" title="Mytitle" align="center" />`
# Becomes
# `![Alt_name](./Images/My_image.png "Mytitle"){width=800 height=800}`
# Notice that the `align` attribute is discarded.
# This markdown size specification is not consistent with Jupyter
# as of v4.3, but can be used by pandoc when converting to latex and pdf.
# """
# parser = Img2mdParser()
# parser.feed(s)
# parser.close()
# outtext = u''
# startpos = 0
# for img in parser.imglist:
# outtext += s[startpos:img.atrdict[]
# outtext += 'data:image/%s;base64,%s'% \
# (img[0][1],str(img[0][0]).lstrip('b\'').rstrip('\''))
# startpos = img[1][1] if len(img)==3 else -1
# outtext += s[startpos:] if startpos != -1 else ''
# return outtext
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class Img2Base64Parser(HTMLParser):
"""Image Parser
Replaces html img file references with base64 encoded strings.
Inherites from HTMLParser, overrides:
- handle_starttag
- handle_endtag
- get_offset
"""
# number of open tags
opentags = None
# list of found imgs
imglist = None
# active img tag
imgtag = None
def __init__(self):
self.imglist = []
self.opentags = 0
HTMLParser.__init__(self)
def get_offset(self):
# Compute startposition in source
lin, offset = self.getpos()
pos = 0
for i in range(lin):
pos = self.data.find('src=',pos) + 5
return pos
def handle_starttag(self, tag, attrs):
# for each tag check if attributes are present and convert src to base64
if self.opentags == 0 and len(attrs)>0:
for atr, data in attrs:
if atr.lower() == 'src':
self.imgtag = tag
self.opentags = 1
with open(data, "rb") as image_file:
encoded_data = base64.b64encode(image_file.read())
extension = os.path.splitext(data)[1][1:].strip().lower()
self.imglist.append([[encoded_data, extension],
[self.get_offset(), self.get_offset()+len(data)]])
return
if tag == self.imgtag:
# found an open img tag but not the starting one
self.opentags += 1
def handle_endtag(self, tag):
if tag == self.imgtag:
# found img tag check if starting one
if self.opentags == 1:
pos = self.get_offset()
self.imglist[-1].append(pos+len(tag)+ 3)
self.opentags -= 1
def feed(self, data):
self.data = data
HTMLParser.feed(self, data)
class Img2mdParser(HTMLParser):
"""Image Parser
Replaces html img reference with markdown.
Inherites from Img2Base64Parser, overrides:
- handle_starttag
- handle_endtag
- get_offset
"""
# number of open tags
opentags = None
# list of found img atrs
attrdict = None
# active img tag
imgtag = None
def __init__(self):
atrdict = {
"alt":None,
"title":None,
"src":None,
"width":None,
"height":None
}
self.opentags = 0
Img2Base64Parser.__init__(self)
def get_offset(self):
# Compute startposition in source
lin, offset = self.getpos()
pos = 0
for i in range(lin-1):
pos = self.data.find('\n',pos) + 1
return pos + offset
def handle_starttag(self, tag, attrs):
# for each tag check if attributes are present and convert src to base64
if self.opentags == 0 and len(attrs)>0:
for atr, data in attrs:
self.imgtag = tag
self.opentags = 1
if atr in self.atrdict:
self.atrdict[atr] = data
self.atrdict[atr].append(self.getpos())
return
if tag == self.imgtag:
# found an open img tag but not the starting one
self.opentags += 1
def handle_endtag(self, tag):
if tag == self.imgtag:
# found img tag check if starting one
if self.opentags == 1:
pos = self.get_offset()
self.imglist[-1].append(pos+len(tag)+ 3)
self.opentags -= 1
def feed(self, data):
self.data = data
HTMLParser.feed(self, data)