簡體   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