How to convert base64 string to image? [duplicate]
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. ;)