How to save an image as a variable?

二次信任 提交于 2020-02-23 03:47:31

问题


Now, I have a python game that has sprites, and it obtains the images from files in its directory. 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

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


回答1:


Continuing @eatmeimadanish's thoughts, you can do it manually:

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.




回答2:


Here is how you can open it using PIL. You need a bytes representation of it, then PIL can open a file like object of it.

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() 


来源:https://stackoverflow.com/questions/52559429/how-to-save-an-image-as-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!