Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open base64 String Image in Jupyter Notebook Without Saving

I have the following image:

enter image description here

Converted to base64, it looks like this:

import base64
filename = 'image.jpg'  

with open(filename, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    image_file.close()

with open("encoded_string.txt", "w") as converted_file:
    converted_file.write(str(encoded_string))
    converted_file.close()

Download the output file (base64) here: https://file.io/NXV7v4

Now, my question is:

How can I retrieve the converted image and show it in jupyter notebook, without having to store it ?

Based on [this][2] question, I tried:

from PIL import Image
import cv2
import io


# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    image = Image.open(io.BytesIO(imgdata))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

stringToRGB(encoded_string)

but I got:

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-43-2564770fa4af> in <module>()
----> 1 stringToRGB(encoded_string)

<ipython-input-42-538f457423e9> in stringToRGB(base64_string)
     18 def stringToRGB(base64_string):
     19     imgdata = base64.b64decode(str(base64_string))
---> 20     image = Image.open(io.BytesIO(imgdata))
     21     return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

~\Anaconda3\lib\site-packages\PIL\Image.py in open(fp, mode)
   2655         warnings.warn(message)
   2656     raise IOError("cannot identify image file %r"
-> 2657                   % (filename if filename else fp))
   2658 
   2659 #

OSError: cannot identify image file <_io.BytesIO object at 0x00000224D6E7D200>
like image 738
henry Avatar asked Apr 07 '19 18:04

henry


People also ask

How do I load an image into Base64?

Images encoded with Base64 can be embedded in HTML by using the <img> tag. This can help to increase the page load time for smaller images by saving the browser from making additional HTTP requests.


2 Answers

Maybe simpler?

from IPython import display
from base64 import b64decode

display.Image(b64decode(base64_data)
like image 88
Leo Avatar answered Oct 05 '22 23:10

Leo


One alternative is to make the browser take care of the decoding and just put the base64 string into an img tag:

from IPython import display

im = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='

display.HTML(f'<img src="data:image/png;base64,{im}" />')
like image 23
Peter Avatar answered Oct 06 '22 01:10

Peter