带有本地 PIL 图像的 Altair 工具提示

Altair tooltip with local PIL image

按照 docs 的官方示例,我可以成功创建一个 altair 散点图,每个点都有一个工具提示:

import altair as alt
import pandas as pd

source = pd.DataFrame.from_records(
    [{'a': 1, 'b': 1, 'image': 'https://altair-viz.github.io/_static/altair-logo-light.png'},
     {'a': 2, 'b': 2, 'image': 'https://avatars.githubusercontent.com/u/11796929?s=200&v=4'}]
)
alt.Chart(source).mark_circle(size=200).encode(
    x='a',
    y='b',
    tooltip=['image']  # Must be a list for the image to render
)

结果如下所示

但是我想使用通过 PIL 加载的本地图像。如果我只是用工具提示中的 PIL 对象替换 URL-string,我会收到错误消息:TypeError: Object of type 'Image' is not JSON serializable.

然后我尝试将图像转换为 JSON 之后

我的代码现在如下所示:

from io import BytesIO
import base64
def image_formatter2(im):
    with BytesIO() as buffer:
        im.save(buffer, 'png')
        data = base64.encodebytes(buffer.getvalue()).decode('utf-8')
    
    return json.dumps(data)
    


temp = some_local_PIL_image.thumbnail((90,90))

source = pd.DataFrame.from_records(
    [{'a': 1, 'b': 1, 'image': image_formatter2(temp)},
     {'a': 2, 'b': 2, 'image': 'https://avatars.githubusercontent.com/u/11796929?s=200&v=4'}]
)
alt.Chart(source).mark_circle(size=200).encode(
    x='a',
    y='b',
    tooltip=['image']  # Must be a list for the image to render
)

我的工具提示现在是空的!如何在工具提示中显示本地图像?


版本信息

IPython          : 7.16.1
jupyter_client   : 7.0.6
jupyter_core     : 4.8.1
altair           : 4.1.0

好的,我有点明白了。必须向数据添加前缀 data:image/png;base64,。现在的代码如下:

import PIL.Image
from io import BytesIO
import base64

def image_formatter2(im):
    with BytesIO() as buffer:
        im.save(buffer, 'png')
        data = base64.encodebytes(buffer.getvalue()).decode('utf-8')
    
    return f"data:image/png;base64,{data}" # <--------- this prefix is crucial
    


temp = some_local_PIL_image.thumbnail((90,90))

source = pd.DataFrame.from_records(
    [{'a': 1, 'b': 1, 'image': image_formatter2(temp)},
     {'a': 2, 'b': 2, 'image': 'https://avatars.githubusercontent.com/u/11796929?s=200&v=4'}]
)
alt.Chart(source).mark_circle(size=200).encode(
    x='a',
    y='b',
    tooltip=['image']  # Must be a list for the image to render
)

结果


因为我不知道 term/syntax 这可能对其他人也有帮助: 必须查找的术语是 Data URLs。这是一个很好的介绍:https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs