Convert base64 to Image in Python

后端 未结 4 1856
走了就别回头了
走了就别回头了 2020-12-03 14:31

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条回答
  • 2020-12-03 15:01

    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

    0 讨论(0)
  • 2020-12-03 15:05

    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 讨论(0)
  • 2020-12-03 15:15

    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.

    0 讨论(0)
  • 2020-12-03 15:17

    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()
    
    0 讨论(0)
提交回复
热议问题