python - 如何将 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')
然后它工作。但是我的图像没有保存在内存中。而且我不想保存它,因为它会降低程序的速度。
解决方案
您可以在内存中将 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 字符串
推荐阅读
- android - 下一个错误是什么意思:“程序类型已存在”
- javascript - Session.cookies.get_dict() 返回一个空字典
- git - 恢复修剪的工作树
- html - 为什么我在 POST 表单中获取 GET 变量?
- .net - VSTO 插件突然无法调用外部方法
- reactjs - 为 React/React-Redux 初学者准备的待办事项列表应用程序功能的想法
- c# - 返回类型为 IEnumerable 而不仅仅是 List?
- java - 在新变量中进行操作与在 println 语句中进行操作之间的区别
- mongodb - MongoDB中的条件$查找?
- sql - 匹配多对多关系