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

2024-02-08

我有来自设备的数据流,我需要将其转换为 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对象或者我是否需要先将其写入磁盘。如果可能的话我想避免写它。

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

总而言之,是否可以从以下位置获取我的 jpeg 文件的 Base64 编码版本:image对象而不先将其写入磁盘?


试试这个代码

图像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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用Python对图像进行base64编码 的相关文章

随机推荐