Python output numpy array as base64 encoded string instead of jpg

Viewed 106

I have a simple Python3 script that is creating an image from a numpy array using the following...

cv2.imwrite("finalImage.jpg", numpyArray) 

This is working correctly but now I am looking to output a base64 encoded string instead of the jpg image.

I know I can convert the output jpg image to a base64 string but is there a way to do this directly so I can skip the extra step of outputting the JPG?

2 Answers
import base64
_, imagebytes = cv2.imencode('.jpg', numpyArray)
print(base64.b64encode(imagebytes))

You can make use of imencode(..) [opencv-doc] to write the image to a memory buffer:

success, buffer = cv2.imencode('.jpg', numpyArray)

You can then for example base64 encode this:

from base64 import b64encode

encoded_image = b64encode(buffer)
Related