Python 使用 base64 编码图像文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3715493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:22:55  来源:igfitidea点击:

Encoding an image file with base64

pythonbase64

提问by rectangletangle

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.

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

EDIT

编辑

I tried this snippet:

我试过这个片段:

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?

我究竟做错了什么?

采纳答案by Jim Brissom

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

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

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

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

编辑:好的,这是您编辑原始问题后的更新。

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

首先,记住在 Windows 上使用路径分隔符时使用原始字符串(字符串前缀为 'r'),以防止意外碰到转义字符。其次,PIL 的 Image.open 要么接受文件名,要么接受类文件(也就是说,对象必须提供 read、seek 和 tell 方法)。

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

话虽如此,您可以使用 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()

回答by John La Rooy

As I said in your previous question, there is no need to base64 encode the string, it will only make the program slower. Just use the repr

正如我在您之前的问题中所说,不需要对字符串进行 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))
...

Now the image is stored as a variable called image_datain a file called image.pyStart a fresh interpreter and import the image_data

现在图像被存储为一个image_data名为image.py启动一个新的解释器并导入 image_data的文件中调用的变量

>>> from image import image_data
>>>

回答by Ivo van der Wijk

With python 2.x, you can trivially encode using .encode:

使用 python 2.x,您可以使用 .encode 进行简单的编码:

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

回答by iChux

Borrowing from what Ivo van der Wijkand gnibblerhave developed earlier, this is a dynamic solution

借鉴Ivo van der Wijkgnibbler之前开发的内容,这是一个动态解决方案

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

You can then decide to compile the output image file with Cythonto make it cool. With this method, you can bundle all your graphics into one module.

然后,您可以决定使用Cython编译输出图像文件以使其更酷。使用这种方法,您可以将所有图形捆绑到一个模块中。

回答by CodeSpeedy

The first answer will print a string with prefix b'. That means your string will be like this b'your_string' To solve this issue please add the following line of code.

第一个答案将打印一个带有前缀 b' 的字符串。这意味着您的字符串将像这样 b'your_string' 要解决此问题,请添加以下代码行。

encoded_string= base64.b64encode(img_file.read())
print(encoded_string.decode('utf-8'))

回答by DooDle Software Solutions

import base64
from PIL import Image
from io import BytesIO

with open("image.jpg", "rb") as image_file:
    data = base64.b64encode(image_file.read())

im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')