How to convert base64 string to image? [duplicate] How to convert base64 string to image? [duplicate] python python

How to convert base64 string to image? [duplicate]


Try this:

import base64imgdata = base64.b64decode(imgstring)filename = 'some_image.jpg'  # I assume you have a way of picking unique filenameswith 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


Return converted image without saving:

from PIL import Imageimport cv2# Take in base64 string and return cv imagedef stringToRGB(base64_string):    imgdata = base64.b64decode(str(base64_string))    image = Image.open(io.BytesIO(imgdata))    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)


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