使用base64编码图像文件

我想要使​​用base64模块将图像编码为一个string。 我遇到了一个问题,但。 如何指定要编码的图像? 我试图使用目录到图像,但是这只是导致目录被编码。 我想要实际的图像文件进行编码。

编辑

我厌倦了这个片段:

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()) 

您必须首先打开文件,然后阅读其内容 – 不能简单地将path传递给编码函数。

编辑:好的,这是你编辑你原来的问题后的更新。

首先,在Windows上使用path分隔符时,请记住使用原始string(以'r'开头的string),以防止意外击中转义字符。 其次,PIL的Image.open或者接受一个文件名,或者一个类似于文件的对象(也就是说,该对象必须提供读取,查找和告诉方法)。

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

 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 2.x,你可以使用.encode进行简单的编码:

 with open("path/to/file.png", "rb") as f: data = f.read() print data.encode("base64") 

正如我在前面的问题中所说的那样,没有必要对string进行base64编码,它只会使程序变慢。 只要使用repr

 >>> with open("images/image.gif", "rb") as fin: ... image_data=fin.read() ... >>> with open("image.py","wb") as fout: ... fout.write("image_data="+repr(image_data)) ... 

现在图像被存储为名为image_data的variables,名为image_data ,启动一个新的解释器并导入image_data

 >>> from image import image_data >>> 

从Ivo van der Wijk和gnibbler早些时候开发的借用,这是一个dynamic的解决scheme

 import cStringIO import PIL.Image image_data = None def imagetopy(image, output_file): with open(image, 'rb') as fin: image_data = fin.read() with open(output_file, 'w') as fout: fout.write('image_data = '+ repr(image_data)) def pytoimage(pyfile): pymodule = __import__(pyfile) img = PIL.Image.open(cStringIO.StringIO(pymodule.image_data)) img.show() if __name__ == '__main__': imagetopy('spot.png', 'wishes.py') pytoimage('wishes') 

然后,您可以决定使用Cython编译输出图像文件,以使其变得酷炫。 使用这种方法,您可以将所有graphics打包到一个模块中。