经过更多搜索,我发现我可以将图像文件放在名为“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'))
我用了另一种方式:
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")
您可以尝试使用这个旧的 GitHub 问题中提供的解决方案: https://github.com/plotly/dash/issues/71
它似乎不是为本地网址构建的:?
如果您想以交互方式执行此操作(例如,如果您想每分钟或其他时间渲染图像)
在布局中包含此 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,
)
您也将其包含在布局中。