【问题标题】:How to save an image as a variable?如何将图像保存为变量?
【发布时间】:2018-09-28 16:31:06
【问题描述】:

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

我使用图像的实际方式是

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

因此,如果您能准确说明如何替换此代码,将会很有帮助

【问题讨论】:

  • tkinter 没有图像对象吗? Qt 有一个,名为 QImage。
  • 但每次都必须从文件中打开图片
  • 而当程序结束时,图像数据会发生什么变化?
  • “如何将我的程序打包成 exe”比“如何将图像放入 python 脚本”要好得多。答案肯定不会是“将所有数据放入你的 python 脚本中”。
  • @Aran-Fey:我觉得你有点苛刻。我认为在某些情况下将一些图像数据嵌入到脚本中是完全合理的。这可能不是最佳做法,但仍然是一个合理的解决方案。

标签: python python-3.x python-imaging-library


【解决方案1】:

继续@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 一起使用。

【讨论】:

【解决方案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() 

【讨论】:

  • img 的值是什么的别名?
  • 你的解释在哪里?
  • 我们终于到了。
猜你喜欢
  • 2020-05-23
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
  • 2022-01-24
  • 2014-12-11
  • 1970-01-01
相关资源
最近更新 更多