How to convert Python numpy array to base64 output
I believe since numpy.array
s support the buffer protocol, you just need the following:
processed_string = base64.b64encode(img)
So, for example:
>>> encoded = b"aGVsbG8sIHdvcmxk">>> img = np.frombuffer(base64.b64decode(encoded), np.uint8)>>> imgarray([104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100], dtype=uint8)>>> img.tobytes()b'hello, world'>>> base64.b64encode(img)b'aGVsbG8sIHdvcmxk'>>>
I have the same problem. After some search and try, my final solution is almost the same as yours.
The only difference is that the base64 encoded string is png
format data, so I need to change it from RGBA
to RGB
channels before converted to np.array:
image = image.convert ("RGB")img = np.array(image)
In the reverse process, you treate the data as JPEG
format, maybe this is the reason why new_image_string
is not identical to base64_image_string
?
from http://www.programcreek.com/2013/09/convert-image-to-string-in-python/ :
import base64with open("t.png", "rb") as imageFile: str = base64.b64encode(imageFile.read()) print str
is binary read