使用 base64 编码图像文件

新手上路,请多包涵

我想使用 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

我究竟做错了什么?

原文由 rectangletangle 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 329
2 个回答

我不确定我是否理解你的问题。我假设您正在按照以下方式做某事:

 import base64

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

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

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

首先,在 Windows 上使用路径定界符时,请记住使用原始字符串(在字符串前加上“r”),以防止不小心碰到转义字符。其次,PIL 的 Image.open 要么接受文件名,要么接受文件名(即对象必须提供读取、查找和告诉方法)。

也就是说,您可以使用 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()

原文由 Jim Brissom 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

我在将 Image 转换为 Base64 字符串时遇到过这种情况。您也可以看看我是如何从那里删除它的。链接在这里 Image to base64 string and fix ‘b from prefix

原文由 CodeSpeedy 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题