在plotly dash中,如何将本地图像文件来源为dash.html.Img?

问题描述 投票:0回答:4
python html image plotly
4个回答
8
投票

经过更多搜索,我发现我可以将图像文件放在名为“assets/”的文件夹中,然后相对于应用程序文件夹引用它。

html.Img(src=r'assets/Plotly_Dash_logo.png', alt='image')

我还可以使用应用程序实例的特殊方法

dash.Dash.get_asset_url()

html.Img(src=app.get_asset_url('my-image.png'))

来源:https://dash.plotly.com/dash-enterprise/static-assets


4
投票

我用了另一种方式:

  • 打开图像文件并读取内容
  • 对数据进行base64编码并解码
  • 在字符串前面添加“data:image/jpg;base64,”(对于 png 格式图像,请将 jpg 替换为 png)
  • 将字符串设置为 src
with open(imgfile, "rb") as image_file:
    img_data = base64.b64encode(image_file.read())
    img_data = img_data.decode()
    img_data = "{}{}".format("data:image/jpg;base64, ", img_data)
    # ...
    html.Img(id="tag_id", src=img_data, alt="my image", width="200", height="400", 
    className="img_class")

0
投票

您可以尝试使用这个旧的 GitHub 问题中提供的解决方案: https://github.com/plotly/dash/issues/71

它似乎不是为本地网址构建的:?


0
投票

如果您想以交互方式执行此操作(例如,如果您想每分钟或其他时间渲染图像)

在布局中包含此 div、img:

html.Div(
    children=[
        html.Img(
            id='figure-image-test',
            # define this in styles.css
            className='figure',
        ),
    ],
    # define this in styles.css
    className='figure-row',
),

更新

src

@app.callback(
    dash.Output(component_id='figure-image-test', component_property='src'),
    dash.Input('interval-component', 'n_intervals'),
)
def update_charts(n_intervals):
    print(f'refreshing {datetime.now()}, {n_intervals}')

    # this will write the image file to `./assets/my_figure.png`
    tmp_filename = f'{os.getcwd()}/assets/my_figure.png'

    # create an image file using matplotlib
    fig = plt.figure(figsize=(6, 4.5))
    ax = fig.add_subplot(1, 1, 1)
    ax.scatter(x, y)
    fig.savefig(tmp_filename)

    return (
        # src should be set to: src='assets/my_figure.png'
        'assets/my_figure.png'
    )

interval-component
应该是

dcc.Interval(
    id='interval-component',
    interval=10 * 1000, # 10 seconds
    n_intervals=0,
)

您也将其包含在布局中。

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