繁体   English   中英

有没有办法在 python 代码上附加图像,使其成为源代码的一部分?

[英]Is there a way of attaching an image on a python code in such a way that it becomes part of the soure code?

我是 python 的初学者,我正在尝试向某人发送我的小 python 程序以及运行代码时将显示的图片。

我试图首先将图像转换为二进制文件,认为我可以将其粘贴到源代码中,但我不确定这是否可行,因为我未能成功完成。

您可以对 JPEG/PNG 图像进行 base64 编码,这将使它成为一个常规(非二进制字符串),如下所示:

base64 -w0 IMAGE.JPG

然后你想将结果放入 Python 变量,所以重复命令但将 output 复制到剪贴板:

base64 -w0 IMAGE.JPG | xclip -selection clipboard    # Linux
base64 -w0 IMAGE.JPG | pbcopy                        # macOS

现在启动 Python 并创建一个名为img的变量并将剪贴板粘贴到其中:

img = 'PASTE'

它看起来像这样:

img = '/9j/4AAQSk...'     # if your image was JPEG
img = 'iVBORw0KGg...'     # if your image was PNG

现在做一些导入:

from PIL import Image
import base64
import io

# Make PIL Image from base64 string
pilImage = Image.open(io.BytesIO(base64.b64decode(img)))

现在你可以用你的图像做你喜欢的事了:

# Print its description and size
print(pilImage)
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x100>

# Save it to local disk
pilImage.save('result.jpg')

您可以在程序的变量中以字节格式保存图片。 然后,您可以使用 io 模块的 BytesIO function 和 plot 将字节转换回类似文件的文件 object 使用 Pillow 库中的图像模块 object。

import io
import PIL.Image

with open("filename.png", "rb") as file:
    img_binary = file.read()

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

要将二进制数据保存在您的程序中而不必从源文件中读取,您需要使用类似 base64 的代码对其进行编码,使用 print() 然后简单地将 output 复制到一个新变量中并从代码中删除文件读取操作。

那看起来像这样:

img_encoded = base64.encodebytes(img_binary)
print(img_binary)

img_encoded = " " # paste the output from the console into the variable

output 会很长,尤其是当您使用大图像时。 我只使用了一个非常小的 png 进行测试。

这是程序最后的样子:

import io
import base64
import PIL.Image

# with open("filename.png", "rb") as file:
#    img_binary = file.read()
# img_encoded = base64.encodebytes(img_binary)

img_encoded = b'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABX[...]'
img = PIL.Image.open(io.BytesIO(base64.decodebytes(img_encoded)))
img.show()

您或许可以让您的 Python 程序从您上传文件的站点(例如 Google Drive、Mega 或 Imgur)下载图像。 这样,您始终可以轻松访问和查看图像,而无需运行程序或例如按照您提到的方法将二进制文件转换回图像。

否则,您总是可以将图像作为字节存储在一个变量中,并让您的程序读取该变量。 我假设您确实希望以这种方式进行,因为这样会更容易分发,因为只有一个文件需要下载和运行。

或者您可以查看pyinstaller ,它是为 python 程序制作的,可以轻松地跨机器分发,无需安装 Python,方法是将其打包为可执行 (.exe) 文件。 这样您就可以通过将图像文件嵌入到程序中来将其包含在一起。 有很多 pyinstaller 的教程,你可以用谷歌搜索:注意。 在运行 pyinstaller 时在参数中包含“--onefile”,因为这会将 package 可执行文件放入一个文件中,您要将其发送给的人可以轻松打开任何人——授予可执行文件可以在用户的上运行操作系统: :)

暂无
暂无

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

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