在Python中添加图片(例如JPG格式)到程序中,你可以使用Pillow库,这是PIL库(Python Imaging Library)的一个更新分支。以下是使用Pillow库添加JPG图片的步骤:
1. 安装Pillow库:
pip install Pillow
2. 在Python代码中导入Pillow库并使用它来打开和显示JPG图片:
from PIL import Image打开图片文件image = Image.open('image.jpg')显示图片image.show()获取图片的尺寸width, height = image.sizeprint(f"Image dimensions: {width} x {height}")如果需要,可以转换图片为灰度图像gray_image = image.convert('L')gray_image.show()

请确保将 `'image.jpg'` 替换为你希望打开的JPG图片的实际文件路径。
如果你使用的是Tkinter图形用户界面库,也可以通过以下方式添加JPG图片:
from PIL import Image, ImageTkimport tkinter as tk创建主窗口root = tk.Tk()打开图片文件image = Image.open('image.jpg')将图片转换为PhotoImage对象photo = ImageTk.PhotoImage(image)创建标签并设置图片label = tk.Label(root, image=photo)label.pack()运行主循环root.mainloop()
同样,确保将 `'image.jpg'` 替换为你的图片文件路径。
