Skip to content

Commit 337bb99

Browse files
author
mikael frosini
committed
Added svg inlining (not clean) ==> pull request
1 parent 7b88cac commit 337bb99

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

ipyplot/_html_helpers.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import numpy as np
99
import shortuuid
1010
from numpy import str_
11+
import urllib
1112

1213
from ._img_helpers import _img_to_base64
1314

@@ -228,14 +229,14 @@ def _display_html(html: str):
228229
display(HTML(_create_html_viewer(html)))
229230
return display(HTML(html))
230231

231-
232232
def _create_img(
233233
image: str or object,
234234
label: str or int,
235235
width: int,
236236
grid_style_uuid: str,
237237
custom_text: str = None,
238-
force_b64: bool = False):
238+
force_b64: bool = False,
239+
inline_svg: bool = True):
239240
"""Helper function to generate HTML code for displaying images along with corresponding texts.
240241
241242
Parameters
@@ -256,7 +257,10 @@ def _create_img(
256257
Do mind that using b64 conversion vs reading directly from filepath will be slower.
257258
You might need to set this to `True` in environments like Google colab.
258259
Defaults to False.
259-
260+
inline_svg : bool, optional
261+
You can force inlining svg images instead of reading them directly from filepaths with HTML.
262+
Defaults to False.
263+
260264
Returns
261265
-------
262266
str
@@ -270,10 +274,13 @@ def _create_img(
270274
img_html += '<h4 style="font-size: 12px; word-wrap: break-word;">%s</h4>' % str(custom_text) # NOQA E501
271275

272276
use_b64 = True
277+
inline_svg = (inline_svg and image[-4:]==".svg")
278+
if inline_svg:
279+
use_b64 = False
273280
# if image is a string (URL) display its URL
274281
if type(image) is str or type(image) is str_:
275282
img_html += '<h4 style="font-size: 9px; padding-left: 10px; padding-right: 10px; width: 95%%; word-wrap: break-word; white-space: normal;">%s</h4>' % (image) # NOQA E501
276-
if not force_b64:
283+
if not force_b64 and not inline_svg:
277284
use_b64 = False
278285
img_html += '<img src="%s"/>' % image
279286
elif "http" in image:
@@ -285,6 +292,10 @@ def _create_img(
285292
if use_b64:
286293
img_html += '<img src="data:image/png;base64,%s"/>' % _img_to_base64(image, width) # NOQA E501
287294

295+
if inline_svg:
296+
string = urllib.parse.quote(open(image,'r').read())
297+
img_html += f'<img src="data:image/svg+xml,{string:s}">'
298+
288299
html = """
289300
<div class="ipyplot-placeholder-div-%(0)s">
290301
<div id="ipyplot-content-div-%(0)s-%(1)s" class="ipyplot-content-div-%(0)s">
@@ -301,7 +312,6 @@ def _create_img(
301312
""" % {'0': grid_style_uuid, '1': img_uuid, '2': label, '3': img_html} # NOQA E501
302313
return html
303314

304-
305315
def _create_imgs_grid(
306316
images: Sequence[object],
307317
labels: Sequence[str or int],

0 commit comments

Comments
 (0)