← 返回首页

Pillow库

📖 正文内容


一、Pillow 库简介

Pillow 是 Python 中用于图像处理的一个强大的第三方库,它是 PIL (Python Imaging Library) 的一个分支,且在 Python 3 环境下得到了更好的支持和维护。通过使用 Pillow,我们可以轻松地打开、操作、编辑和保存各种格式的图像文件。

二、安装 Pillow 库

首先确保你已安装了 pip(Python 包管理器)。在命令行中输入以下命令来安装 Pillow:

pip3 install pillow

三、基础操作示例

打开和显示图片

from PIL import Image # 打开一张图片 img = Image.open("example.jpg") # 显示图片(需要在 Jupyter notebook 或者有 GUI 支持的环境中) img.show()

保存图片

# 将图片以另一种格式保存(例如转换为 JPEG 格式) img.save("example_converted.jpg", "JPEG")

获取图片尺寸

width, height = img.size print(f"Image dimensions: {width}x{height}")

四、图像处理实例

缩放图像

# 缩放图像至指定大小 resized_img = img.resize((new_width, new_height)) resized_img.save("example_resized.jpg")

旋转图像

# 顺时针旋转图像 40 度 rotated_img = img.rotate(40) rotated_img.save("example_rotated.jpg")

裁剪图像

# 裁剪图像的一部分,前面两个为左上角坐标,后面两个是右下角坐标 box = (left, upper, right, lower) cropped_img = img.crop(box) cropped_img.save("example_cropped.jpg")

色彩转换与滤镜

# 将图像转换为灰度图像 gray_img = img.convert("L") gray_img.save("example_gray.jpg")
# 应用 PIL 内置滤镜 filtered_img = img.filter(ImageFilter.BLUR) filtered_img.save("example_blurred.jpg")

五、进阶案例

批量转换图像格式

import os for filename in os.listdir("images_folder"):     if filename.endswith(".png"):         img = Image.open(os.path.join("images_folder", filename))         new_filename = filename.replace(".png", ".jpg")         img.save(os.path.join("output_folder", new_filename), "JPEG")

图像像素操作

# 获取图像的像素数据并进行修改 pixels = img.load() for x in range(img.width):     for y in range(img.height):         r, g, b = pixels[x, y]         # 假设将所有像素颜色变淡一半         pixels[x, y] = (r // 2, g // 2, b // 2) # 修改后的像素存回原图 img.save("example_modified.jpg")

图像缩略图

Pillow库的thumbnail()方法可以生成图像的缩略图。我们可以指定缩略图的最大尺寸。
from PIL import Image # 打开图像文件 image = Image.open("image.jpg") # 生成缩略图 thumbnail_size = (200, 200) image.thumbnail(thumbnail_size) # 保存缩略图 image.save("thumbnail.jpg")
在上面的例子中,我们使用thumbnail()方法生成200x200像素的缩略图,并将缩略图保存为"thumbnail.jpg"文件。

添加水印

Pillow库提供了丰富的绘图功能,可以在图像上添加文本、形状等元素,实现水印效果。
from PIL import Image, ImageDraw, ImageFont # 打开图像文件 image = Image.open("image.jpg") # 创建绘图对象 draw = ImageDraw.Draw(image) # 添加水印文本 text = "Watermark" font = ImageFont.truetype("arial.ttf", 36) text_size = draw.textsize(text, font) text_position = (image.width - text_size[0], image.height - text_size[1]) draw.text(text_position, text, fill=(255, 255, 255), font=font) # 保存带水印的图像 image.save("watermarked_image.jpg")
在上面的例子中,我们使用

ImageDraw

模块创建了一个绘图对象,并使用

text()

方法在图像上添加了水印文本。通过指定文本的位置、颜色和字体等参数,我们可以自定义水印效果。


💡 示例代码

<div style='--en-codeblock:true;--en-blockId:gXFFS2Sgu6D;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>pip3 install pillow
</div>

<div style='--en-codeblock:true;--en-blockId:fbc_Se5xhMz;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>from PIL import Image
# 打开一张图片
img = Image.open("example.jpg")
# 显示图片(需要在 Jupyter notebook 或者有 GUI 支持的环境中)
img.show()
</div>

<div style='--en-codeblock:true;--en-blockId:zge6QallfbW;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 将图片以另一种格式保存(例如转换为 JPEG 格式)
img.save("example_converted.jpg", "JPEG")
</div>

<div style='--en-codeblock:true;--en-blockId:kpc6RarZ0Ny;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>width, height = img.size
print(f"Image dimensions: {width}x{height}")
</div>

<div style='--en-codeblock:true;--en-blockId:_sBBRaDKXIt;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 缩放图像至指定大小
resized_img = img.resize((new_width, new_height))
resized_img.save("example_resized.jpg")
</div>

<div style='--en-codeblock:true;--en-blockId:WowxROzxw_Z;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 顺时针旋转图像 40 度
rotated_img = img.rotate(40)
rotated_img.save("example_rotated.jpg")
</div>

<div style='--en-codeblock:true;--en-blockId:9386QCELp6O;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 裁剪图像的一部分,前面两个为左上角坐标,后面两个是右下角坐标
box = (left, upper, right, lower)
cropped_img = img.crop(box)
cropped_img.save("example_cropped.jpg")
</div>

<div style='--en-codeblock:true;--en-blockId:95BySaTeypg;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 将图像转换为灰度图像
gray_img = img.convert("L")
gray_img.save("example_gray.jpg")
</div>

<div style='--en-codeblock:true;--en-blockId:vJkQQGEVH3y;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 应用 PIL 内置滤镜
filtered_img = img.filter(ImageFilter.BLUR)
filtered_img.save("example_blurred.jpg")
</div>

<div style='--en-codeblock:true;--en-blockId:3dsiT-hDxkz;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>import os

for filename in os.listdir("images_folder"):
    if filename.endswith(".png"):
        img = Image.open(os.path.join("images_folder", filename))
        new_filename = filename.replace(".png", ".jpg")
        img.save(os.path.join("output_folder", new_filename), "JPEG")
</div>

<div style='--en-codeblock:true;--en-blockId:0aJITex3yqv;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 获取图像的像素数据并进行修改
pixels = img.load()
for x in range(img.width):
    for y in range(img.height):
        r, g, b = pixels[x, y]
        # 假设将所有像素颜色变淡一半
        pixels[x, y] = (r // 2, g // 2, b // 2)

# 修改后的像素存回原图
img.save("example_modified.jpg")
</div>

<div style='--en-codeblock:true;--en-blockId:ibO2Re09MIh;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>from PIL import Image
# 打开图像文件
image = Image.open("image.jpg")
# 生成缩略图
thumbnail_size = (200, 200)
image.thumbnail(thumbnail_size)
# 保存缩略图
image.save("thumbnail.jpg")</div>

<div style='--en-codeblock:true;--en-blockId:wgf4RKLq0La;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>from PIL import Image, ImageDraw, ImageFont
# 打开图像文件
image = Image.open("image.jpg")
# 创建绘图对象
draw = ImageDraw.Draw(image)
# 添加水印文本
text = "Watermark"
font = ImageFont.truetype("arial.ttf", 36)
text_size = draw.textsize(text, font)
text_position = (image.width - text_size[0], image.height - text_size[1])
draw.text(text_position, text, fill=(255, 255, 255), font=font)
# 保存带水印的图像
image.save("watermarked_image.jpg")</div>

💭 技巧提示

💡

📚 参考资料

💬 评论交流

👤
用户 A 2026-03-25

这个技巧很实用,感谢分享!