[英]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. StackOverflow上已经有几种解决方案,可以对图像和base64字符串进行解码和编码。 But most of them need IO between disk which is time wasted.
但是它们中的大多数都需要磁盘之间的IO,这很浪费时间。 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). 关键是如何通过编码(例如JPEG或PNG编码,而不是base64编码)将numpy数组转换为
bytes
对象。 Certainly, we can do this by saving and reading the image with imsave
and imread
, but PIL provides a more direct method: 当然,我们可以通过使用
imsave
和imread
保存和读取图像来做到这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
The key problem here is how to read an image from decoded bytes
. 这里的关键问题是如何从解码的
bytes
读取图像。 The plugin imageio
in skimage
provides such a method: imageio
中的skimage
插件提供了这样一种方法:
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: 请注意,上述方法需要python软件包
imageio
,可以通过pip安装该软件包:
pip install imageio
pip安装imageio
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.