Ask Your Question

Revision history [back]

As an illustration of @slelievre's answer, I wrote a couple functions to read in the SVG (or other graphics) source to convert the result into Base64.

def base64(obj, file_format="svg"):
    Generates Base64 encoding of the graphic in the requested file_format.
    if not isinstance(obj,Graphics):
        raise TypeError("Only graphics may be encoded as base64")
    if file_format not in ["svg", "png"]:
        raise ValueError("Invalid file format")
    filename = tmp_filename(ext=f'.{file_format}')
    with open(filename, 'rb') as f:
        from base64 import b64encode
        b64 = b64encode('utf-8')
    return b64

def data_url(obj, file_format="svg"):
    Generates Data URL representing the graphic in the requested file_format.
    b64 = base64(obj, file_format=file_format)
    if file_format=="svg":
        file_format = "svg+xml"
    return f"data:image/{file_format};base64,{b64}"

f = lambda x, y: sin(x + y) + cos(x + y)
p = plot_slope_field(f, (-3, 3), (-3, 3))
du = data_url(p,file_format="png")
from IPython.core.display import display, HTML
display(HTML(f"<img src='{du}'>"))
print(f"<img src='{du}'>")