使用 base64 编码图像文件

2022-01-21 00:00:00 python base64

问题描述

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

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:Python26seriph1.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:Python26GUI1.2.9.py", line 473, in <module>
    app = simpleapp_tk(None)
  File "C:Python26GUI1.2.9.py", line 14, in __init__
    self.initialize()
  File "C:Python26GUI1.2.9.py", line 431, in initialize
    self.image = ImageTk.PhotoImage(Image.open(UUU))
  File "C:Python26libsite-packagesPILImage.py", line 1952, in open
    fp = __builtin__.open(fp, "rb")
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

我做错了什么?


解决方案

我不确定我是否理解你的问题.我假设你正在做一些事情:

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.

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

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

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

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

相关文章