开发者

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 Im开发者_开发知识库age.


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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜