gpt4 book ai didi

python - 使用 base64 编码图像文件

转载 作者:IT老高 更新时间:2023-10-28 12:30:03 25 4
gpt4 key购买 nike

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

编辑

我试过这个片段:

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

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

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

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

话虽如此,您可以使用 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 - 使用 base64 编码图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3715493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com