PyScript调用API获取图片无法在网页正常显示的问题求助
PyScript接口获取图片无法渲染问题解决
核心问题点
现有代码无法显示图片的原因共两点:
<py-script>标签的output属性无法直接解析matplotlib的AxesImage对象(即代码中赋值给imgplot的变量),仅支持直接输出字符串、DOM节点、matplotlib显式生成的画布对象- 仅调用
plt.imshow()只会把图片数据加载到matplotlib内存缓冲区,不会触发画布渲染流程,根本没有生成可嵌入网页的可视化内容;最后一行直接写imgplot也没有任何输出作用,只是声明了一个变量。
修正方法
不需要修改py-env里的依赖配置,仅调整<py-script>块内的逻辑即可:
- 读取到存储图片像素的uint8类型numpy数组后,先创建matplotlib画布实例,隐藏多余的坐标轴刻度、边框,避免出现无关UI
- 将图片数组渲染到画布上
- 调用
plt.show()触发生成可嵌入网页的画布,PyScript会自动把画布内容输出到你指定id为image的容器中
修正后可运行完整代码
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> <py-env> - matplotlib - imageio </py-env> </head> <body> <h1>PyScript - images from API</h1> <div> <p> This webpage fetches a cat image from cataas and displays it below. </p> </div> <div id="image"></div> <py-script output="image"> from pyodide.http import pyfetch from io import BytesIO import matplotlib.pyplot as plt import imageio.v3 as iio # 请求接口获取图片字节流 response = await pyfetch(url="https://cataas.com/cat", method="GET") # 将字节流解析为uint8格式的numpy像素数组 img = iio.imread(BytesIO(await response.bytes()), index=None) # 初始化画布,隐藏坐标轴 plt.figure() plt.axis('off') # 将图片渲染到画布 plt.imshow(img) # 输出渲染完成的画布到页面容器 plt.show() </py-script> </body> </html>
补充优化方案:如果不想引入matplotlib依赖提升页面加载速度,可以直接把接口返回的图片字节流转为base64编码,手动拼接
<img>标签插入到目标div中,不需要经过numpy数组解析、matplotlib渲染的流程,加载速度会快很多。
内容的提问来源于stack exchange,提问作者Luigi Palumbo
相关产品推荐
相关产品推荐

