Skip to content

Commit ab4a26d

Browse files
author
Adam Kemp
committed
Add support for embedding images as data URIs.
1 parent 7fb280c commit ab4a26d

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

bpy/handlers/base.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
import warnings
2727
from abc import ABCMeta, abstractmethod
2828
from hashlib import md5
29-
from os.path import basename, splitext
29+
from os.path import basename, splitext, exists
30+
from base64 import b64encode
3031

3132
HAS_SMARTYPANTS = False
3233
try:
@@ -57,6 +58,8 @@ class BaseHandler():
5758
re.DOTALL | re.MULTILINE)
5859
RE_HEADER = re.compile(r'.*?([a-zA-Z0-9_-]+)\s*[=:]\s*(.*)\s*')
5960

61+
RE_IMG = re.compile(r'(<img.*?)src="([^"]*)"(.*?>)')
62+
6063
def __init__(self, filename, options=None):
6164

6265
self.filename = filename
@@ -230,6 +233,9 @@ def generate(self, markup=None):
230233
Attr = smartypants.Attr
231234
html = smartypants.smartypants(html, Attr.set1 | Attr.w)
232235

236+
if self.options.get('embed_images', False):
237+
html = self.embed_images(html)
238+
233239
return html
234240

235241
def generate_header(self, header=None):
@@ -348,3 +354,23 @@ def write(self, forced=False):
348354
with codecs.open(self.filename, 'w', 'utf8') as f:
349355
f.write(self.source)
350356
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

Comments
 (0)