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?
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.