如何使用python对图像进行base64编码 [英] How to base64 encode an image using python

查看:474
本文介绍了如何使用python对图像进行base64编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a stream of data that comes from a device and I need to convert it into a jpeg and then base64 encode it to transfer it over the network.

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

My Python 2.7 code so far looks like this:

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格式保存到磁盘中.

I can see I have the image I want and can save it to the disk in jpeg format.

我不了解的是我是否可以对image对象中的图像进行base64编码,或者是否需要先将其写入磁盘.我想尽可能避免编写它.

What I don't understand is if I can base64 encode the image from the image object or if I need to write it to the disk first. I would like to avoid writing it if possible.

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

The 2nd question I have is what is PIL doing in this process? Is it taking the data and putting the required special codes into the file to make it a jpeg file? I think the answer tot his is yes as I can change the file extension to .bmp and the correct file is written on the disk.

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

So in summary, is it possible to get a base64 encoded version of my jpeg file from the image object without writing it to disk first?

推荐答案

尝试此代码

图像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对图像进行base64编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆