用Python操作图像,核心是Pillow库。它支持图像加载、保存、尺寸调整、裁剪、旋转、滤镜应用、颜色增强和文字水印添加。安装命令为pip install Pillow,通过Image.open()读取图片,获取format、size、mode属性后可进行各类变换,如resize()调整大小、crop()裁剪、rotate()旋转,并使用filter()应用模糊等滤镜,ImageEnhance调整亮度对比度,ImageDraw.Draw()配合ImageFont添加文字水印,最终用save()输出新图像,整个流程高效直观,适合批量处理与自动化任务。

用Python操作图像,最直接、最有效的方法就是利用Pillow库。它其实是Python Imaging Library (PIL) 的一个分支,但更活跃,也更好地支持现代Python版本,能让你轻松实现图像的加载、保存、尺寸调整、裁剪、滤镜应用,甚至是绘制文字和图形等一系列操作。可以说,Pillow就是Python在图像处理领域的瑞士军刀,无论是简单的图片转换,还是复杂的自动化任务,它都能胜任。
要用Python操作图像,核心就是Pillow库。它的工作流程通常是这样的:首先,你需要安装Pillow。然后,通过
Image.open()
Image
Image.save()
刚开始接触图像处理时,我发现很多人,包括我自己,都会有点迷茫,到底是用PIL还是Pillow?其实很简单,现在就用Pillow。它是PIL的现代化和积极维护版本,支持Python 3,功能也更完善。安装它,简直是小菜一碟,命令行里敲一行代码就行:
pip install Pillow
安装好之后,我们就可以开始玩转图片了。最基础的,就是怎么把一张图片读进来,再怎么存出去。这听起来简单,但却是所有图像操作的基石。
立即学习“Python免费学习笔记(深入)”;
from PIL import Image
try:
# 加载图片
img = Image.open('example.jpg')
print(f"原始图片格式: {img.format}, 尺寸: {img.size}, 模式: {img.mode}")
# 显示图片(这会调用系统默认的图片查看器,方便调试)
# img.show()
# 将图片保存为不同的格式,比如PNG
img.save('example_output.png')
print("图片已成功保存为 example_output.png")
# 如果你想把图片转成灰度图再保存
gray_img = img.convert('L') # 'L' 代表灰度模式
gray_img.save('example_gray.jpg')
print("图片已成功保存为 example_gray.jpg")
except FileNotFoundError:
print("错误:example.jpg 文件未找到。请确保图片文件存在于脚本同级目录。")
except Exception as e:
print(f"处理图片时发生错误: {e}")这里值得一提的是
img.format
img.size
img.mode
format
size
(width, height)
mode
RGB
L
RGBA
RGBA
图片处理,最常见的需求无非就是调整大小、裁剪和旋转。Pillow在这些方面做得非常出色,提供了直观的API。但这里有个小细节,Pillow的很多操作,比如
resize
Image
from PIL import Image
try:
img = Image.open('example.jpg')
# 1. 调整尺寸 (Resize)
# 定义新的尺寸,比如宽度500像素,高度按比例缩放
# 或者直接指定 (width, height)
new_width = 500
new_height = int(img.size[1] * (new_width / img.size[0]))
resized_img = img.resize((new_width, new_height), Image.LANCZOS) # LANCZOS是高质量的重采样滤波器
resized_img.save('example_resized.jpg')
print(f"图片已调整尺寸并保存为 example_resized.jpg (新尺寸: {resized_img.size})")
# 2. 裁剪 (Crop)
# 定义裁剪区域:(left, upper, right, lower)
# 比如从左上角开始,裁剪一个200x200的区域
crop_area = (0, 0, 200, 200)
cropped_img = img.crop(crop_area)
cropped_img.save('example_cropped.jpg')
print(f"图片已裁剪并保存为 example_cropped.jpg (裁剪区域: {crop_area})")
# 3. 旋转 (Rotate)
# 旋转45度,并扩展画布以适应旋转后的图像
rotated_img = img.rotate(45, expand=True)
rotated_img.save('example_rotated.jpg')
print("图片已旋转45度并保存为 example_rotated.jpg")
except FileNotFoundError:
print("错误:example.jpg 文件未找到。")
except Exception as e:
print(f"处理图片时发生错误: {e}")在
resize
Image.LANCZOS
LANCZOS
Image.NEAREST
Image.BILINEAR
crop
rotate
expand=True
除了基础的几何变换,Pillow还能让我们对图像的视觉效果进行深度定制。比如应用各种滤镜,调整颜色,或者给图片加上文字水印。这些功能在生成海报、处理用户上传的头像,或者为图片添加版权信息时非常有用。
from PIL import Image, ImageFilter, ImageEnhance, ImageDraw, ImageFont
try:
img = Image.open('example.jpg')
# 1. 应用滤镜 (Filters)
# 比如模糊滤镜
blurred_img = img.filter(ImageFilter.BLUR)
blurred_img.save('example_blurred.jpg')
print("图片已应用模糊滤镜并保存为 example_blurred.jpg")
# 更多滤镜:SHARPEN, CONTOUR, EMBOSS, FIND_EDGES等
# sharpened_img = img.filter(ImageFilter.SHARPEN)
# sharpened_img.save('example_sharpened.jpg')
# 2. 颜色调整 (Color Enhancement)
# 调整亮度、对比度、色彩饱和度、锐度
enhancer = ImageEnhance.Brightness(img)
bright_img = enhancer.enhance(1.5) # 亮度增加50%
bright_img.save('example_bright.jpg')
print("图片亮度已调整并保存为 example_bright.jpg")
enhancer = ImageEnhance.Contrast(img)
contrast_img = enhancer.enhance(1.8) # 对比度增加80%
contrast_img.save('example_contrast.jpg')
print("图片对比度已调整并保存为 example_contrast.jpg")
# 3. 添加文字水印 (Text Watermark)
# 确保图片是RGB模式,如果不是,需要转换,因为Draw只支持RGB或RGBA
if img.mode != 'RGB':
img = img.convert('RGB')
draw = ImageDraw.Draw(img)
text = "Python & Pillow"
font_size = 30
# 尝试加载一个字体文件,如果系统没有这个字体,可能需要指定路径
try:
font = ImageFont.truetype("arial.ttf", font_size) # Windows系统常见字体
except IOError:
# 如果arial.ttf找不到,使用Pillow的默认字体
font = ImageFont.load_default()
print("警告: arial.ttf 未找到,使用默认字体。")
# 计算文字位置,比如右下角
text_width, text_height = draw.textsize(text, font=font) # draw.textsize 在Pillow 9.0+ 废弃,推荐使用 font.getbbox()
# 推荐的计算方式(Pillow 9.0+)
# bbox = font.getbbox(text)
# text_width = bbox[2] - bbox[0]
# text_height = bbox[3] - bbox[1]
x = img.width - text_width - 10 # 距离右边缘10像素
y = img.height - text_height - 10 # 距离下边缘10像素
draw.text((x, y), text, font=font, fill=(255, 255, 255, 128)) # 白色半透明文字
img.save('example_watermarked.jpg')
print("图片已添加文字水印并保存为 example_watermarked.jpg")
except FileNotFoundError:
print("错误:example.jpg 文件未找到。")
except Exception as e:
print(f"处理图片时发生错误: {e}")在给图片添加文字水印时,
ImageDraw
ImageFont.truetype
fill
(R, G, B, A)
以上就是如何用Python操作图像(PIL/Pillow库)?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号