如果文件系统中不存在图像,如何将图像保存在代码中(通过 pickle、dill 或其他字节码)并保存到文件?

How can I save an image in code (via pickle, dill, or other bytecode) and save to file if not exist in a file system?

如果文件系统中不存在图像,我如何将图像保存在代码中(通过 pickle、dill 或其他字节码)并保存到文件中? Python3.6.5.

为了使 Tkinter 应用程序正常工作,我需要出示两张照片。它们可能会或可能不会一直出现在设备上,因此我需要根据需要创建它们。但是,我不知道该怎么做才不会损坏文件。有什么建议吗?

当前代码:

with open("0.png", 'rb') as f:
    temp = f.read()
    CogFile = pickle.dumps(temp, pickle.HIGHEST_PROTOCOL)
    print(FileData)
    pickle.dump(FileData, open("1.png", 'wb'), pickle.HIGHEST_PROTOCOL)

with open("0.gif", 'rb') as F:
    temp = F.read()
    CogFile = pickle.dumps(temp, pickle.HIGHEST_PROTOCOL)
    print(FileData)
    pickle.dump(FileData, open("1.gif", 'wb'), pickle.HIGHEST_PROTOCOL)

您可以将图像嵌入到 python 文件中。为此,默认图像位需要采用语法适合 .py 文件的非二进制格式。这是一个编码器文件,您可以 运行 一次,然后将结果作为变量粘贴到 .py 文件中。它执行 base64 编码以将二进制文件转换为 acscii,并将其全部包装在 python bytes 对象中。

import sys
import base64

try:
    var = sys.argv[1]
    fn = sys.argv[2]
    with open(fn, 'rb') as fp:
        print(var, '= b"""\')
        for line in base64.encodebytes(fp.read()).split(b'\n'):
            if line:
                print(line.decode('ascii'))
        print('"""')
except (IndexError, OSError):
    print("usage: pyencode.py variable_name file_to_encode")

举个例子

$ python3 pyencoder.py dft_png stackoverlow.png 
dft_png = b"""\
iVBORw0KGgoAAAANSUhEUgAAAGkAAABpCAMAAAAOXP0IAAAAe1BMVEX////0gCS8u7u5uLjNzMzy
8vL6z7j0eQf0eg/5v6Dk5OTZ2dn0fh/0fRvzdQD//PnCwcH+9/P83cj+9e396971j0P3nVv3o2f9
5tb4soL82sH4rnr6yKb5u5T1jDv0hCnzbwD2lk/6y673p2771Lf5uo31iy71iDP5wZrUFssbAAAC
yElEQV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