Home > Software design >  Python - How do you display base64 images during a for loop in Jupyter Notebook?
Python - How do you display base64 images during a for loop in Jupyter Notebook?

Time:08-11

I'm trying to display a list of dicts where one of the keys is to a base64 string.

So far, I have been unable to display the base64 strings as images during a for loop and not within a DataFrame.

My code:

from IPython import display
from base64 import b64decode 

display.Image(b64decode(b64_str))

Unfortunately, while this works on a single code cell running a single base64 string, it does not show any image during the for loop.

# imagine this is being done in a Jupyter Notebook code cell
arr = [{"b64_str": "...", "title": "product1"},...]

for item in arr:
    display.Image(b64decode(b64_str))

This also fails to show any image:

# again, imagine this is being done in a Jupyter Notebook code cell
arr = [{"b64_str": "...", "title": "product1"},...]

for item in arr:
    print( display.Image(b64decode(b64_str)) )

How can I get the base64 strings to display properly during the loop?

CodePudding user response:

You're missing a call to IPython.display.display:

enter image description here

from IPython import display

jupyter = 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/44px-Jupyter_logo.svg.png'
python = 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/110px-Python-logo-notext.svg.png'

for path in [jupyter, python]:
    display.display(display.Image(path))
  • Related