我想使用base64模块将图像编码为字符串.不过我遇到了一个问题.如何指定要编码的图像?我try 使用目录来创建图像,但这只会导致目录被编码.我想对实际的图像文件进行编码.

EDIT

我试过这个片段:

with open("C:\Python26\seriph1.BMP", "rb") as f:
    data12 = f.read()
    UU = data12.encode("base64")
    UUU = base64.b64decode(UU)

    print UUU

    self.image = ImageTk.PhotoImage(Image.open(UUU))

但我得到了以下错误:

Traceback (most recent call last):
  File "<string>", line 245, in run_nodebug
  File "C:\Python26\GUI1.2.9.py", line 473, in <module>
    app = simpleapp_tk(None)
  File "C:\Python26\GUI1.2.9.py", line 14, in __init__
    self.initialize()
  File "C:\Python26\GUI1.2.9.py", line 431, in initialize
    self.image = ImageTk.PhotoImage(Image.open(UUU))
  File "C:\Python26\lib\site-packages\PIL\Image.py", line 1952, in open
    fp = __builtin__.open(fp, "rb")
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

我做错了什么?

推荐答案

我不太明白你的问题.我想你是在做以下事情:

import base64

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

当然,您必须首先打开文件并读取其内容-不能简单地将路径传递给encode函数.

Edit:

首先,在Windows上使用路径分隔符时,请记住使用原始字符串(字符串前缀为"r"),以防止意外地碰到转义字符.第二,皮尔的形象.open要么接受文件名,要么接受类似的文件(也就是说,对象必须提供读取、查找和告知方法).

也就是说,您可以使用cStringIO从内存缓冲区创建这样一个对象:

import cStringIO
import PIL.Image

# assume data contains your decoded image
file_like = cStringIO.StringIO(data)

img = PIL.Image.open(file_like)
img.show()

Python相关问答推荐

Python:根据创建时间合并两个收件箱

如何从. text中进行pip安装跳过无法访问的库

使用Python C API重新启动Python解释器

如何使用上下文管理器创建类的实例?

从DataFrame.apply创建DataFrame

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

为什么默认情况下所有Python类都是可调用的?

如何将一个动态分配的C数组转换为Numpy数组,并在C扩展模块中返回给Python

Pandas计数符合某些条件的特定列的数量

如何在表中添加重复的列?

Pandas Loc Select 到NaN和值列表

什么是最好的方法来切割一个相框到一个面具的第一个实例?

无法连接到Keycloat服务器

CommandeError:模块numba没有属性generated_jit''''

在matplotlib中删除子图之间的间隙_mosaic

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

未调用自定义JSON编码器

python—telegraph—bot send_voice发送空文件

搜索按钮不工作,Python tkinter

如何在Great Table中处理inf和nans