There're already several solutions on StackOverflow to decode and encode image and base64 string. But most of them need IO between disk which is time wasted. Are there any solutions to encode and decode just in memory?
1 Answer
Encoding
The key point is how to convert a numpy array to bytes object with encoding (such as JPEG or PNG encoding, not base64 encoding). Certainly, we can do this by saving and reading the image with imsave and imread, but PIL provides a more direct method:
from PIL import Image
import skimage
import base64
def encode(image) -> str:
# convert image to bytes
with BytesIO() as output_bytes:
PIL_image = Image.fromarray(skimage.img_as_ubyte(image))
PIL_image.save(output_bytes, 'JPEG') # Note JPG is not a vaild type here
bytes_data = output_bytes.getvalue()
# encode bytes to base64 string
base64_str = str(base64.b64encode(bytes_data), 'utf-8')
return base64_str
Decoding
The key problem here is how to read an image from decoded bytes. The plugin imageio in skimage provides such a method:
import base64
import skimage.io
def decode(base64_string):
if isinstance(base64_string, bytes):
base64_string = base64_string.decode("utf-8")
imgdata = base64.b64decode(base64_string)
img = skimage.io.imread(imgdata, plugin='imageio')
return img
Notice that above method needs python package imageio which can be installed by pip:
pip install imageio