Skip to main content
 首页 » 编程设计

python之如何将图像保存为变量

2025年05月04日22zengkefu

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

我使用图像的实际方式是

image = PIL.Image.open('image.gif') 

所以如果你能准确地知道如何替换这段代码,那将会很有帮助

请您参考如下方法:

继续@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() 

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