简体   繁体   English

如何将图像保存为变量?

[英]How to save an image as a variable?

Now, I have a python game that has sprites, and it obtains the images from files in its directory.现在,我有一个带有精灵的 python 游戏,它从其目录中的文件中获取图像。 I want to make it such that I do not even need the files.我想让我什至不需要这些文件。 Somehow, to pre-store the image in a variable so that i can call it from within the program, without the help of the additional .gif files不知何故,将图像预先存储在一个变量中,以便我可以从程序中调用它,而无需额外的 .gif 文件的帮助

The actual way i am using the image is我使用图像的实际方式是

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

So it would be helpful if you could be precise about how to replace this code因此,如果您能准确地了解如何替换此代码,将会有所帮助

Continuing @eatmeimadanish's thoughts, you can do it manually:继续@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()

This is with tkinter PhotoImage though, but I'm sure you can figure out how to make it work with PIL.虽然这是与 tkinter PhotoImage 一起使用的,但我相信您可以弄清楚如何使其与 PIL 一起使用。

Here is how you can open it using PIL.以下是如何使用 PIL 打开它。 You need a bytes representation of it, then PIL can open a file like object of it.您需要它的字节表示,然后 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() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM