2

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 2

3
import base64
_, imagebytes = cv2.imencode('.jpg', numpyArray)
print(base64.b64encode(imagebytes))
Sign up to request clarification or add additional context in comments.

Comments

2

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)

1 Comment

Thanks for that, perfect solution and works well. Thanks for the links to the doc, reading them, now to make sure I fully understand what is happening

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.