How to convert base64 string to image?

PythonBase64

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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 

Solution 3 - Python

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. ;)

Solution 4 - Python

This should do the trick:

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

Solution 5 - Python

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');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomarsafwanyView Question on Stackoverflow
Solution 1 - PythonrmunnView Answer on Stackoverflow
Solution 2 - PythonJumabek AlikhanovView Answer on Stackoverflow
Solution 3 - PythonFernando Jorge MotaView Answer on Stackoverflow
Solution 4 - PythonpypatView Answer on Stackoverflow
Solution 5 - PythonAnthony AnyanwuView Answer on Stackoverflow