Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode and decode between base64 string and numpy array?

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?

like image 794
huangbiubiu Avatar asked Nov 29 '25 11:11

huangbiubiu


1 Answers

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

like image 131
huangbiubiu Avatar answered Dec 02 '25 03:12

huangbiubiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!