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