引言
使用Python标准库读取JPG图片
安装PIL库
虽然PIL库不是Python的标准库,但它是处理图像的强大工具。首先,确保您已经安装了PIL库。
pip install pillow
读取JPG图片
from PIL import Image
# 打开JPG图片文件
with Image.open('example.jpg') as img:
# 显示图片
img.show()
# 获取图片尺寸
width, height = img.size
print(f"图片尺寸: {width}x{height}")
# 获取图片模式
mode = img.mode
print(f"图片模式: {mode}")
# 获取图片数据
pixels = list(img.getdata())
print(f"像素数据长度: {len(pixels)}")
使用第三方库Pillow读取JPG图片
安装Pillow库
如果您还没有安装Pillow库,可以使用以下命令进行安装:
pip install pillow
读取JPG图片
from PIL import Image
# 打开JPG图片文件
img = Image.open('example.jpg')
# 显示图片
img.show()
# 获取图片尺寸
width, height = img.size
print(f"图片尺寸: {width}x{height}")
# 获取图片模式
mode = img.mode
print(f"图片模式: {mode}")
# 获取图片数据
pixels = list(img.getdata())
print(f"像素数据长度: {len(pixels)}")