How to convert base64 string to image? [duplicate]

Posted on

Question :

How to convert base64 string to image? [duplicate]

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 #1:

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 gets closed when you exit the with statement
# Now save the value of filename to your database
Answered By: rmunn

Answer #2:

Return converted image without saving:

from PIL import Image
import cv2

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

Answer #3:

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+")

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

Simple. Very simple. 😉

Answered By: Fernando Mota

Answer #4:

This should do the trick:

image = open("image.png", "wb")
Answered By: pypat

Answer #5:

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

Leave a Reply

Your email address will not be published. Required fields are marked *