与编码的base64图像文件 [英] Encoding an image file with base64

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

问题描述

我要带code图像到使用中的Base64模块的字符串。我遇到了一个问题,虽然。如何指定我想成为EN codeD的形象呢?我尝试使用目录的图像,但只是导致目录是EN codeD。我想实际的图像文件是EN codeD。

I want to encode an image into a string using the base64 module. I've ran into a problem though. How do I specify the image I want to be encoded? I tried using the directory to the image, but that simply leads to the directory being encoded. I want the actual image file to be encoded.

修改

我厌倦了这样的片段:

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

但我得到以下错误:

but I get the following error:

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

我是什么做错了吗?

What am I doing wrong?

推荐答案

我不知道我理解你的问题。我假设你正在沿着线做的事情:

I'm not sure I understand your question. I assume you are doing something along the lines of:

import base64

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

您必须首先当然是打开文件,并阅读其内容 - 你不能简单的路径传递给EN code函数

You have to open the file first of course, and read its contents - you cannot simply pass the path to the encode function.

编辑:
好吧,这里是一个更新您编辑你原来的问题了。

Ok, here is an update after you have edited your original question.

首先,当使用路径分隔符在Windows上,以prevent意外击中转义字符记得要使用原始字符串(preFIX带R的字符串)。其次,PIL的Image.open要么接受一个文件名,或一个类文件(即对象必须提供阅读,寻求和告知的方法)。

First of all, remember to use raw strings (prefix the string with 'r') when using path delimiters on Windows, to prevent accidentally hitting an escape character. Second, PIL's Image.open either accepts a filename, or a file-like (that is, the object has to provide read, seek and tell methods).

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

That being said, you can use cStringIO to create such an object from a memory buffer:

import cStringIO
import PIL.Image

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

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

这篇关于与编码的base64图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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