如何在base64字符串和numpy数组之间进行编码和解码?

Hua*_*eng 2 python base64 image scikit-image

StackOverflow 上已经有几种解决方案来解码和编码图像和 base64 字符串。但是他们中的大多数都需要磁盘之间的IO,这很浪费时间。是否有任何解决方案可以仅在内存中进行编码和解码?

Hua*_*eng 6

编码

关键是如何将一个numpy数组转换为bytes带有编码的对象(比如JPEG或PNG编码,而不是base64编码)。当然,我们可以通过使用imsave和保存和读取图像来做到这一点imread,但 PIL 提供了一个更直接的方法:

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
Run Code Online (Sandbox Code Playgroud)

解码

这里的关键问题是如何从解码的bytes. 插件imageioskimage提供了这样一个方法:

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
Run Code Online (Sandbox Code Playgroud)

请注意,上述方法需要imageio可以通过 pip 安装的python 包:

pip 安装 imageio