How to convert base64 string to image?

Question:

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?

Asked By: omarsafwany

||

Answers:

This should do the trick:

image = open("image.png", "wb")
image.write(base64string.decode('base64'))
image.close()
Answered By: pypat

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
Answered By: rmunn

Just use the method .decode('base64') and go to be happy.

You need, too, to detect the mimetype/extension of the image, as you can save it correctly, in a brief example, you can use the code below for a django view:

def receive_image(req):
    image_filename = req.REQUEST["image_filename"] # A field from the Android device
    image_data = req.REQUEST["image_data"].decode("base64") # The data image
    handler = open(image_filename, "wb+")
    handler.write(image_data)
    handler.close()

And, after this, use the file saved as you want.

Simple. Very simple. 😉

Answered By: Fernando Jorge Mota

Convert base64_string into opencv (RGB):

from PIL import Image
import cv2

# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    img = Image.open(io.BytesIO(imgdata))
    opencv_img= cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
    return opencv_img 
Answered By: Jumabek Alikhanov

You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:

import cv2
import numpy as np

def save(encoded_data, filename):
    nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
    return cv2.imwrite(filename, img)

Then somewhere in your code you can use it like this:

save(base_64_string, 'testfile.png');
save(base_64_string, 'testfile.jpg');
save(base_64_string, 'testfile.bmp');
Answered By: Anthony Anyanwu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.