Convert numpy array into a bytestring readable by the src of an html img tag

Viewed 884

I have a numpy array that I want to display through the src attribute of an img html component, kinda like this exemple :

def get_placeholder_thumbnail_html_value():
    encoded_image = base64.b64encode(open("../assets/placeholder_thumbnail.png", 'rb').read())
    return 'data:image/png;base64,{}'.format(encoded_image.decode())

The returned string can then be sent to be assigned to the src attribute of the corresponding img html component (I do it with a plotly dash callback).

Question : In the example above I do it from a png image on the server. How could I do the same from a numpy ndarray ?

def get_thumbnail_html_value_from_ndarray(ndarray):
    return 'data:image/png;base64,{}'.format(<what here ?>)

It could be parsed to jpg or anything else, as long as the html can interpret the image properly.

EDIT : I could save it on the server as a png file then load it back with the example above, but it seems very inefficient, so I don't like this workaround.

1 Answers

I had basically the same problem, with the added condition that the image format needed to be png. Here's my solution using cv2 and base64:

import cv2
import base64

def ndarray_to_b64(ndarray):
    """
    converts a np ndarray to a b64 string readable by html-img tags 
    """
    img = cv2.cvtColor(ndarray, cv2.COLOR_RGB2BGR)
    _, buffer = cv2.imencode('.png', img)
    return base64.b64encode(buffer).decode('utf-8')

Related