如何将图像保存为变量?

2024-05-17 18:44:17 发布

您现在位置:Python中文网/ 问答频道 /正文

现在,我有一个python游戏,它有精灵,它从目录中的文件中获取图像。我想让它成为我甚至不需要文件。以某种方式,将图像预存储在一个变量中,这样我就可以在程序中调用它,而无需其他.gif文件的帮助

我使用图像的实际方式是

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

所以如果你能精确地知道如何替换这些代码,那将是很有帮助的


Tags: 文件代码图像image程序目录游戏pil
2条回答

下面是如何使用PIL打开它。你需要它的字节表示,然后PIL可以打开它的一个类似文件的对象。在

import base64
from PIL import Image
import io

with open("picture.png", "rb") as file:
    img = base64.b64encode(file.read())

img = Image.open(io.BytesIO(img))
img.show() 

继续eatmeimdanish的想法:您可以手动执行:

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一起工作。在

相关问题 更多 >