3

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?

zindarod
6,4763 gold badges35 silver badges61 bronze badges
asked May 21, 2018 at 7:43

1 Answer 1

9

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

answered May 21, 2018 at 7:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.