我有一个来自设备的数据流,我需要将其转换为 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/