Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base64 to Image in Python

I have a mongoDB database and I recover base64 data which corresponds to my Image.

I don't know how to convert base64 data to an Image.

like image 753
kschaeffler Avatar asked Mar 20 '11 13:03

kschaeffler


People also ask

What is base64 to image?

Base64 encoding is a way to encode binary data in ASCII text. It's primarily used to store or transfer images, audio files, and other media online. It is also often used when there are limitations on the characters that can be used in a filename for various reasons.

How do you decode base64 encoding in Python?

Using Python to decode strings: Decoding Base64 string is exactly opposite to that of encoding. First we convert the Base64 strings into unencoded data bytes followed by conversion into bytes-like object into a string. The below example depicts the decoding of the above example encode string output.


1 Answers

Building on Christians answer, here the full circle:

import base64

jpgtxt = base64.encodestring(open("in.jpg","rb").read())

f = open("jpg1_b64.txt", "w")
f.write(jpgtxt)
f.close()

# ----
newjpgtxt = open("jpg1_b64.txt","rb").read()

g = open("out.jpg", "w")
g.write(base64.decodestring(newjpgtxt))
g.close()

or this way:

jpgtxt = open('in.jpg','rb').read().encode('base64').replace('\n','')

f = open("jpg1_b64.txt", "w")
f.write(jpgtxt)
f.close()

# ----
newjpgtxt = open("jpg1_b64.txt","rb").read()

g = open("out.jpg", "w")
g.write(newjpgtxt.decode('base64'))
g.close()
like image 78
dirkk0 Avatar answered Oct 16 '22 21:10

dirkk0