繁体   English   中英

如何将 Python 中的图像编码为 Base64?

[英]How to encode a image in Python to Base64?

我有一个 3 维 numpy 数组的 RGB 图像。

我目前正在使用这个

base64.b64encode(img).decode('utf-8')

但是当我将输出复制/粘贴到这个网站https://codebeautify.org/base64-to-image-converter

它不会将图像转换回来。

但是如果我使用这个代码:

import base64
with open("my_image.jpg", "rb") as img_file:
    my_string = base64.b64encode(img_file.read())
my_string = my_string.decode('utf-8')

那么它的工作原理。 但是我的图像没有保存在内存中。 而且我不想保存它,因为它会降低程序的速度。

您可以将 RGB 直接编码为内存中的 jpg 并为此创建 base64 编码。

jpg_img = cv2.imencode('.jpg', img)
b64_string = base64.b64encode(jpg_img[1]).decode('utf-8')

完整示例:

import cv2
import base64
img = cv2.imread('test_image.jpg')
jpg_img = cv2.imencode('.jpg', img)
b64_string = base64.b64encode(jpg_img[1]).decode('utf-8')

base 64 字符串应该可以用https://codebeautify.org/base64-to-image-converter解码

试试这个方法:- RGB 图像 base64 编码/解码

def encode_img(img_fn):
with open(img_fn, "rb") as f:
data = f.read()
return data.encode("base64")

import cStringIO
import PIL.Image

def decode_img(img_base64):
decode_str = img_base64.decode("base64")
file_like = cStringIO.StringIO(decode_str)
img = PIL.Image.open(file_like)
# rgb_img[c, r] is the pixel values.
rgb_img = img.convert("RGB")
return rgb_img

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM