Render a captcha image to dash app

Hi there,

I am trying to adding a captcha image to my dash app.

I am using captcha · PyPI library to generate the image and I can successfully create the image.

The problem is that the image is a “BytesIO object of _io module” and I do not know how to display this image directly the web app, for example using html.Img.

I could save the image to the server as a .jpg file and then I can read it from the server and display it in the app.

However, as I might have multiple users at the same time, I do not want to write-and-read the image from the server but directly display to the user.

Do you have any suggestion on how I could do that?

Many thanks!

html.Image supports special base64 encoded strings preceding with the image mime type. you should be able to convert to base64 from bytesio with a base64 module. I forget exactly which namespace this is in (i’m on my phone) but hopefully this gives you a clue :slight_smile:

Great, thanks for your quick reply. I ll look for a base64 module to convert the bytesio image.

Once I get the image “variable” converted in base64, how do I pass it to the html.Image dash component? simply like html.Img(image_var)? (sorry I am not very fluent in html :slight_smile: )

thanks in advance!

I don’t recall exactly where I saw this in the forums a long time ago, but its worked for me since. Here is what I do:

path = 'path_to_logo'  # usually this is in the assets folder
img_tunel = base64.b64encode(open(path, 'rb').read())
image = html.Img(src='data:image/png;base64,{}'.format(img_tunel.decode()))
3 Likes

Thanks for the quick reply!

That worked for me!