如何将图像保存为变量?

ѕня*_*gнι 1 python python-imaging-library python-3.x

现在,我有一个带有精灵的 python 游戏,它从其目录中的文件中获取图像。我想让它甚至不需要这些文件。不知何故,将图像预先存储在一个变量中,以便我可以在程序中调用它,而无需额外的 .gif 文件的帮助

我使用图像的实际方式是

image = PIL.Image.open('image.gif')
Run Code Online (Sandbox Code Playgroud)

因此,如果您能准确地了解如何替换此代码,将会有所帮助

fig*_*eam 5

继续@eatmeimadanish 的想法,你可以手动完成:

import base64

with open('image.gif', 'rb') as imagefile:
    base64string = base64.b64encode(imagefile.read()).decode('ascii')

print(base64string)  # print base64string to console
# Will look something like:
# iVBORw0KGgoAAAANS  ...  qQMAAAAASUVORK5CYII=

# or save it to a file
with open('testfile.txt', 'w') as outputfile:
    outputfile.write(base64string)


# Then make a simple test program:

from tkinter import *
root = Tk()

# Paste the ascii representation into the program
photo = 'iVBORw0KGgoAAAANS ... qQMAAAAASUVORK5CYII='

img = PhotoImage(data=photo)
label = Label(root, image=img).pack()
Run Code Online (Sandbox Code Playgroud)

虽然这是与 tkinter PhotoImage 一起使用的,但我相信您可以弄清楚如何使其与 PIL 一起使用。