|
26 | 26 | import warnings
|
27 | 27 | from abc import ABCMeta, abstractmethod
|
28 | 28 | from hashlib import md5
|
29 |
| -from os.path import basename, splitext |
| 29 | +from os.path import basename, splitext, exists |
| 30 | +from base64 import b64encode |
30 | 31 |
|
31 | 32 | HAS_SMARTYPANTS = False
|
32 | 33 | try:
|
@@ -57,6 +58,8 @@ class BaseHandler():
|
57 | 58 | re.DOTALL | re.MULTILINE)
|
58 | 59 | RE_HEADER = re.compile(r'.*?([a-zA-Z0-9_-]+)\s*[=:]\s*(.*)\s*')
|
59 | 60 |
|
| 61 | + RE_IMG = re.compile(r'(<img.*?)src="([^"]*)"(.*?>)') |
| 62 | + |
60 | 63 | def __init__(self, filename, options=None):
|
61 | 64 |
|
62 | 65 | self.filename = filename
|
@@ -230,6 +233,9 @@ def generate(self, markup=None):
|
230 | 233 | Attr = smartypants.Attr
|
231 | 234 | html = smartypants.smartypants(html, Attr.set1 | Attr.w)
|
232 | 235 |
|
| 236 | + if self.options.get('embed_images', False): |
| 237 | + html = self.embed_images(html) |
| 238 | + |
233 | 239 | return html
|
234 | 240 |
|
235 | 241 | def generate_header(self, header=None):
|
@@ -348,3 +354,23 @@ def write(self, forced=False):
|
348 | 354 | with codecs.open(self.filename, 'w', 'utf8') as f:
|
349 | 355 | f.write(self.source)
|
350 | 356 | self.modified = False
|
| 357 | + |
| 358 | + def embed_images(self, html): |
| 359 | + return self.RE_IMG.sub(self.embed_image, html) |
| 360 | + |
| 361 | + def embed_image(self, match): |
| 362 | + img_name = match.group(2) |
| 363 | + if exists(img_name): |
| 364 | + img_prefix = match.group(1) |
| 365 | + src_attr = "src=\"" + self.encode_image(img_name) + "\"" |
| 366 | + img_suffix = match.group(3) |
| 367 | + return img_prefix + src_attr + img_suffix |
| 368 | + else: |
| 369 | + return match.group(0) |
| 370 | + |
| 371 | + def encode_image(self, name): |
| 372 | + with open(name, "rb") as f: |
| 373 | + image_data = f.read() |
| 374 | + ext = splitext(name)[1].lstrip('.') |
| 375 | + encoded_image = b64encode(image_data) |
| 376 | + return "data:image/" + ext + ";base64," + encoded_image |
0 commit comments