How to convert base64 string to image?

omarsafwany picture omarsafwany · Apr 25, 2013 · Viewed 108.6k times · Source

I'm converting an image to base64 string and sending it from android device to the server. Now, I need to change that string back to an image and save it in the database.

Any help?

Answer

rmunn picture rmunn · Apr 25, 2013

Try this:

import base64
imgdata = base64.b64decode(imgstring)
filename = 'some_image.jpg'  # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
    f.write(imgdata)
# f gets closed when you exit the with statement
# Now save the value of filename to your database