python - 如何使用python对图像进行base64编码

标签 python python-2.7 encoding base64 python-imaging-library

我有一个来自设备的数据流,我需要将其转换为 jpeg,然后对其进行 base64 编码以通过网络传输。

到目前为止,我的 Python 2.7 代码如下所示:

from PIL import Image
import io

image = Image.open(io.BytesIO(self.imagebuffer)) # Image buffer contains the image data from the device.
image.save("test.jpg") # Writes the image to the disk in jpeg format
image.show() # Opens the image using the OS image view

我可以看到我有我想要的图像,可以将它以 jpeg 格式保存到磁盘。

我不明白的是,我是否可以对 image 对象中的图像进行 base64 编码,或者我是否需要先将其写入磁盘。如果可能的话,我想避免写它。

我的第二个问题是 PIL 在此过程中做了什么?是获取数据并将所需的特殊代码放入文件中以使其成为 jpeg 文件吗?我认为他的答案是,因为我可以将文件扩展名更改为 .bmp,然后正确的文件将写入磁盘。

总而言之,是否可以从 image 对象中获取我的 jpeg 文件的 base64 编码版本,而无需先将其写入磁盘?

最佳答案

试试这个代码

图片base64编码格式

Python代码:

import os
import base64

image = 'test.jpg'

encoded_string = ""
with open(image, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    file = encoded_string

关于python - 如何使用python对图像进行base64编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50369637/

相关文章:

python - 在 Pandas 和 NumPy 中处理 0 和 -0

java - 如何从以 latin1 编码的结果集中以 UTF-8 编码字符串

python - 订购两台已排序的发电机,无需进口

python - 如何使用 Flask 使页面内容动态化?

django - 无法连接到 amqp ://guest:**@127. 0.0.1:5672//: [Errno 111] 连接被拒绝

Java aes key 到 32 字节字符串表示

Python Scrapy不返回中文字符

python - 正则表达式仅匹配从左到右阅读的最后一次出现

python - Scipy t 检验统计数据中的一个样本?

python - 在字典中存储逻辑条件并将它们传递给 if 语句