Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django bytesIO to base64 String & return as JSON

Tags:

I am using python 3 & I have this code, trying to get base64 out of stream and returnn as json - but not working.

       stream = BytesIO()        img.save(stream,format='png')        return base64.b64encode(stream.getvalue()) 

in my view, I have:

hm =mymap()     strHM = hm.generate(data) return HttpResponse(json.dumps({"img": strHM}),content_type="application/json"  ) 

getting error is not JSON serializable. base64.b64encode(stream.getvalue()) seems giving bytes

like image 370
user903772 Avatar asked Dec 02 '14 04:12

user903772


People also ask

How do I get Base64 encoded strings?

In JavaScript there are two functions respectively for decoding and encoding Base64 strings: btoa() : creates a Base64-encoded ASCII string from a "string" of binary data ("btoa" should be read as "binary to ASCII"). atob() : decodes a Base64-encoded string ("atob" should be read as "ASCII to binary").

How do I encode strings to Base64 in Python?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.

How do you convert binary to Base64?

Click on the URL button, Enter URL and Submit. This tool supports loading the Binary File to transform to Base64. Click on the Upload button and select File. Binary to Base64 Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

How does Base64 decode work?

Decoding base64First, you remove any padding characters from the end of the encoded string. Then, you translate each base64 character back to their six-bit binary representation. Finally, you divide the bits into byte-sized (eight-bit) chunks and translate the data back to its original format.


1 Answers

In Python 3.x, base64.b64encode accepts a bytes object and returns a bytes object.

>>> base64.b64encode(b'a') b'YQ==' >>> base64.b64encode(b'a').decode() 'YQ==' 

You need to convert it to str object, using bytes.decode:

return base64.b64encode(stream.getvalue()).decode() 
like image 145
falsetru Avatar answered Oct 02 '22 21:10

falsetru