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

5

我有一个三维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')

然后它就能运行了。但是我的图像没有保存在内存中。我不想保存它,因为这会降低程序的速度。

那我是不是应该先保存图像,例如 cv2.imread('img.jpg',img) 然后再读取它? - Tom Holland
如果您想查看编码过程的输出,请输入以下内容:print image_64_encode - Rahul Kr Daman
@TomHolland 其他程序期望什么?我认为它不期望以Base64打包的原始未压缩字节。 - AKX
它只期望一个base64字符串。 - Tom Holland
@TomHolland 我不明白。img_file.read()是将图像文件读入内存。如果您的文件在磁盘上,您可以使用以下代码行:base64.b64encode(img_file.read()).decode('utf-8')来创建图像的有效base64表示形式。您不需要cv2。 - mjspier
显示剩余8条评论
2个回答

12

您可以直接在内存中将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')

这个base64字符串应该可以通过https://codebeautify.org/base64-to-image-converter进行解码。


我知道的,不是所有英雄都穿斗篷! - Tom Holland

0

尝试这种方法:RGB图像的Base64编码/解码

import cStringIO
import PIL.Image

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

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

错误:'utf-8'编解码器无法解码位置0的字节0xff:起始字节无效。 - Tom Holland
我使用了 encode_img(img),其中 img 是一个三维 RGB 图像。 - Tom Holland
1
如果您想查看编码过程的输出,请输入以下内容:打印 image_64_encode - Rahul Kr Daman
这种方法的问题在于当你使用pathlib.Path(img_fn).read_text().encode("base64")时更加明显...也就是说,encode函数取决于对象类型。而在这里,img_fn根本没有被读取为图像。 - user8395964

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接