Skip to content

Commit

Permalink
Added svg inlining (not clean) ==> pull request
Browse files Browse the repository at this point in the history
  • Loading branch information
mikael frosini committed Nov 30, 2020
1 parent 7b88cac commit 337bb99
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions ipyplot/_html_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import numpy as np
import shortuuid
from numpy import str_
import urllib

from ._img_helpers import _img_to_base64

Expand Down Expand Up @@ -228,14 +229,14 @@ def _display_html(html: str):
display(HTML(_create_html_viewer(html)))
return display(HTML(html))


def _create_img(
image: str or object,
label: str or int,
width: int,
grid_style_uuid: str,
custom_text: str = None,
force_b64: bool = False):
force_b64: bool = False,
inline_svg: bool = True):
"""Helper function to generate HTML code for displaying images along with corresponding texts.
Parameters
Expand All @@ -256,7 +257,10 @@ def _create_img(
Do mind that using b64 conversion vs reading directly from filepath will be slower.
You might need to set this to `True` in environments like Google colab.
Defaults to False.
inline_svg : bool, optional
You can force inlining svg images instead of reading them directly from filepaths with HTML.
Defaults to False.
Returns
-------
str
Expand All @@ -270,10 +274,13 @@ def _create_img(
img_html += '<h4 style="font-size: 12px; word-wrap: break-word;">%s</h4>' % str(custom_text) # NOQA E501

use_b64 = True
inline_svg = (inline_svg and image[-4:]==".svg")
if inline_svg:
use_b64 = False
# if image is a string (URL) display its URL
if type(image) is str or type(image) is str_:
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
if not force_b64:
if not force_b64 and not inline_svg:
use_b64 = False
img_html += '<img src="%s"/>' % image
elif "http" in image:
Expand All @@ -285,6 +292,10 @@ def _create_img(
if use_b64:
img_html += '<img src="data:image/png;base64,%s"/>' % _img_to_base64(image, width) # NOQA E501

if inline_svg:
string = urllib.parse.quote(open(image,'r').read())
img_html += f'<img src="data:image/svg+xml,{string:s}">'

html = """
<div class="ipyplot-placeholder-div-%(0)s">
<div id="ipyplot-content-div-%(0)s-%(1)s" class="ipyplot-content-div-%(0)s">
Expand All @@ -301,7 +312,6 @@ def _create_img(
""" % {'0': grid_style_uuid, '1': img_uuid, '2': label, '3': img_html} # NOQA E501
return html


def _create_imgs_grid(
images: Sequence[object],
labels: Sequence[str or int],
Expand Down

0 comments on commit 337bb99

Please sign in to comment.