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

问题描述 投票:0回答:1

按照 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 字符串,我会收到错误:

TypeError: Object of type 'Image' is not JSON serializable

然后我尝试按照此SO答案将图像转换为JSON

我的代码现在如下所示:

import 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
python jupyter-notebook python-imaging-library altair
1个回答
4
投票

好吧,我大概明白了。必须在数据中添加前缀

data:image/png;base64,
。现在代码如下:

import PIL.Image
from io import BytesIO
import base64
import json

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
)

结果


因为我不知道术语/语法,这也可能对其他人有帮助: 人们必须寻找的术语是

Data URLs
。这是一个很好的介绍:https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

© www.soinside.com 2019 - 2024. All rights reserved.