我是 python 的初学者,我正在尝试向某人发送我的小 python 程序以及代码运行时将显示的图片。
我尝试首先将图像转换为二进制文件,认为我可以将其粘贴到源代码中,但我不确定这是否可能,因为我未能成功做到这一点。
您可以将图片以字节格式保存在程序的变量中。然后,您可以使用 io 模块的 BytesIO 函数将字节转换回类似文件的对象,并使用 Pillow 库中的 Image 模块绘制该对象。
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() ,然后只需将输出复制到新变量中并从代码中删除文件读取操作.
看起来像这样:
img_encoded = base64.encodebytes(img_binary)
print(img_binary)
img_encoded = " " # paste the output from the console into the variable
输出会很长,特别是当您使用大图像时。我只使用了一个非常小的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()
您可以对 JPEG/PNG 图像进行 Base64 编码,将其转换为常规(非二进制字符串),如下所示:
base64 -w0 IMAGE.JPG
然后您想要将结果放入 Python 变量中,因此请重复该命令,但将输出复制到剪贴板:
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')
您也许可以让 Python 程序从您上传文件的网站(例如 Google Drive、Mega 或 Imgur)下载图像。这样,您始终可以轻松访问和查看图像,而无需运行程序,或者例如按照您提到的方法将二进制文件转换回图像。
否则,您始终可以将图像作为字节存储在变量中,并让程序读取该变量。我假设您确实希望这样做,因为这样会更容易分发,因为只有一个文件需要下载和运行。
或者你可以看看pyinstaller,它是为了让Python程序可以轻松地跨机器分发而设计的,而无需通过将Python打包为可执行(.exe)文件来安装Python!这样您就可以通过将图像文件嵌入到程序中来将其包含在一起。有很多关于 pyinstaller 的教程,你可以用谷歌搜索。注意:运行 pyinstaller 时,请在参数中包含“--onefile”,因为这会将可执行文件打包到一个文件中,您将其发送给的人可以轻松打开该文件——授予可执行文件可以运行的权限用户的操作系统。 :)
除了 1 个小小的 type-o 之外,什么 CaptainException 完全有效。
img_encoded = base64.encodebytes(img_binary) print(img_binary) img_encoded = " " # paste the output from the console into the variable
print(image_binary)
应该是print(img_encoded)
。
fullname = r'C:\path\to\image.ext'
with open(fullname, "rb") as file:
binary_image = file.read()
ecoded_image = encodebytes(binary_image)
splitlines = ecoded_image.splitlines()
for i in range(len(splitlines)):
if not i:
print(f'ecoded_image = ({splitlines[i]}')
elif i == len(splitlines) - 1:
print(f'{splitlines[i]})'.rjust(len(splitlines[i]) + 20))
else:
print(f'{splitlines[i]}'.rjust(len(splitlines[i]) + 19))
img = Image.open(BytesIO(decodebytes(ecoded_image)))
img.show()