15
votes

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.

4
How was the image put into the database? Once you know that, just reverse the process. - David Heffernan
the image come from Android device. - kschaeffler
the android convert the image in base64 and store it into the database. my task is to recover these data and convert them to an image - kschaeffler
i think you have just to decode your data using base64.b64decode and write it to a file and you will have your image . - mouad
@Karl I don't think you understood my comment. - David Heffernan

4 Answers

6
votes

If you'd like to use that in a webpage, you can just put the base64 encoded image into a HTML file.

See wikipedia for more info

22
votes

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()
8
votes

You can try this:

import base64 
png_recovered = base64.decodestring(png_b64text)

'png_b64text' contains the text from your mongoDB image field.

Then you just write "png_recovered" to a file:

f = open("temp.png", "w")
f.write(png_recovered)
f.close()

Just replace 'png' with the correct format.

1
votes

Your image file(jpeg/png) is encoded to base64 and encoded base64 string is stored in your mongo db. First decode the base64 string

import base64
image_binary=base64.decodestring(recovered_string_from_mongo_db)

Now image_binary contains your image binary, write this binary to file

with open('image.extension','wb') as f:
    f.write(image_binary)

Where extension is your image file extension.