I am trying to fetch image from a URL and display it in the browser using pyiodide and javascript and below is my code:
<!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 <a href="https://cataas.com/#/", target="_blank">cataas</a> and displays it below.
</p>
</div>
<div id="image"></div>
<py-script output="image">
from pyodide.http import pyfetch
import asyncio
from io import BytesIO
import matplotlib.pyplot as plt
import imageio.v3 as iio
import io, base64
response = await pyfetch(url="https://cataas.com/cat", method="GET")
img = iio.imread(BytesIO(await response.bytes()), index=None)
plt.imshow(img)
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
img_str = 'data:image/png;base64,' + base64.b64encode(buf.read()).decode('UTF-8')
<!-- imgplot = plt.imshow(img)
imgplot -->
</py-script>
</body>
<div id="textfield">A matplotlib figure:</div>
<div id="pyplotdiv"><img id="pyplotfigure"/></div>
<script>
document.getElementById("pyplotfigure").src=pyodide.globals.img_str
</script>
</html>
Here I am using pyscript which runs on pyiodide backend to open and plot image using matplotlib and then I am converting the image to base64 string in PNG format and then accessing the JS elements from python and replacing the src of JS element with this base64. However for some reason the image is not being displayed in HTML page. I tried printing the image using print statement to check whether it is loading well or not. The print statement was printing pixel values showing the image is loading well.