首页 > 解决方案 > 如何将 Python 中的图像编码为 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')

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

标签: python

解决方案


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

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


推荐阅读