Pillow:修订间差异
无编辑摘要 |
无编辑摘要 |
||
| (未显示同一用户的1个中间版本) | |||
| 第138行: | 第138行: | ||
old_w, old_h = img.size | old_w, old_h = img.size | ||
if old_w/old_h > max_w/max_h: | if old_w/old_h > max_w/max_h: | ||
img_new = img.resize( (int(max_w), int( | img_new = img.resize( (int(max_w), int(old_h * max_w / old_w)) ) | ||
else: | else: | ||
img_new = img.resize( (int( | img_new = img.resize( (int(old_w * max_h / old_h), int(max_h)) ) | ||
return img_new | return img_new | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| 第178行: | 第178行: | ||
}} | }} | ||
==示例== | |||
===缩放目录所有图片=== | |||
<syntaxhighlight lang="python" > | |||
import os | |||
from PIL import Image | |||
def resize_images_recursive(input_folder, output_folder=None): | |||
if output_folder is None: | |||
output_folder = input_folder + '_1200' | |||
def process_image(input_path, output_path): | |||
try: | |||
with Image.open(input_path) as img: | |||
# 计算新的高度,保持宽高比 | |||
width = 1200 | |||
ratio = width / float(img.size[0]) | |||
height = int(float(img.size[1]) * ratio) | |||
# 只有当原图宽度大于1200时才进行缩放 | |||
if img.size[0] > 1200: | |||
resized_img = img.resize((width, height), Image.Resampling.LANCZOS) | |||
resized_img.save(output_path, quality=95) | |||
else: | |||
# 如果原图小于1200px,直接复制 | |||
img.save(output_path) | |||
return True | |||
except Exception as e: | |||
print(f"处理图片 {os.path.basename(input_path)} 时出错: {str(e)}") | |||
return False | |||
def process_directory(current_input_dir, current_output_dir): | |||
# 创建对应的输出目录 | |||
if not os.path.exists(current_output_dir): | |||
os.makedirs(current_output_dir) | |||
# 遍历当前目录下的所有文件和文件夹 | |||
for item in os.listdir(current_input_dir): | |||
input_path = os.path.join(current_input_dir, item) | |||
output_path = os.path.join(current_output_dir, item) | |||
if os.path.isfile(input_path): | |||
# 处理图片文件 | |||
if item.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.webp')): | |||
process_image(input_path, output_path) | |||
elif os.path.isdir(input_path): | |||
# 递归处理子文件夹 | |||
process_directory(input_path, output_path) | |||
# 开始处理根目录 | |||
process_directory(input_folder, output_folder) | |||
print(f"处理完成!输出文件夹: {output_folder}") | |||
# 使用示例 | |||
input_folder = r"D:\Download\测试" # 替换为你的输入文件夹路径 | |||
resize_images_recursive(input_folder) # 使用默认输出文件夹 | |||
# 或者指定输出文件夹 | |||
# resize_images(input_folder, "path/to/your/output/folder") | |||
</syntaxhighlight> | |||
==资源== | ==资源== | ||
===官网=== | ===官网=== | ||
2025年4月22日 (二) 12:35的最新版本
Pillow是一个Python的图像处理库,PIL(Python Imaging Library)2011年停止更新,随后Pillow分支了PIL并添加了Python 3的支持,现在成为PIL的替代品。
简介
时间轴
安装
使用pip安装:
pip install --upgrade pip
pip install --upgrade Pillow
了解更多 >> Pillow 文档:安装
快速入门
图片格式转换
from PIL import Image
im = Image.open("test.webp")
print(im.size, im.format) # 打印图片尺寸,格式
im.show() # 显示图片
im.save("test.jpg")
了解更多 >> Pillow 文档:Image类的使用
Image类
生成Image类
| 名称 | 描述 | 示例 |
|---|---|---|
| open() | 从图像文件生成Image对象 PIL.Image.open(fp, mode='r', formats=None)
|
from PIL import Image
im = Image.open("test.jpg")
|
| new() | 生成一个新的Image对象 PIL.Image.new(mode, size, color=0)
|
im_new = Image.new('RGB',(1200,1200), 'white')
|
| frombytes() |
属性
以下示例使用如下代码:
from PIL import Image
im = Image.open("test.jpg")
print(im.format)
| 名称 | 描述 | 示例 |
|---|---|---|
| filename | 文件名 | |
| format | 文件格式 | im.format 返回'jpg'
|
| size | ||
了解更多 >> Pillow 文档:Image属性
方法
| 名称 | 描述 | 示例 |
|---|---|---|
| save() | 保存图片。 | |
| crop() | 裁剪图片。 输入参数4元组,坐标为(左、上、右、 下),其中 (0, 0) 中的 左上角,数值为像素。 | box = (100, 100, 400, 400)
region = im.crop(box)
先使用rembg抠图,再裁剪掉多余的边。透明度通道0为透明,255为不透明,计算分别行和列,不为0的起始和终止坐标即可切割。 import numpy as np
from PIL import Image
from rembg import remove
im = Image.open('3.jpg')
# 抠图
im = remove(im, alpha_matting=True, alpha_matting_foreground_threshold=120)
r,g,b,alpha = im.split()
alpha_arr = np.array(alpha) #透明度通道数组
x_start = np.nonzero(alpha_arr.sum(axis=0))[0][0]
x_end = np.nonzero(alpha_arr.sum(axis=0))[0][-1]
y_start = np.nonzero(alpha_arr.sum(axis=1))[0][0]
y_end = np.nonzero(alpha_arr.sum(axis=1))[0][-1]
im.crop((x_start, y_start, x_end, y_end))
|
| resize() | 调整图片大小。 | im.resize( (200,500) ),调整图片尺寸为200x500。自定义一个调整大小函数 def resize_max(img, max_size=(500,500)):
# 调整图片,一边等比缩放,不会变形。
max_w, max_h = max_size
old_w, old_h = img.size
if old_w/old_h > max_w/max_h:
img_new = img.resize( (int(max_w), int(old_h * max_w / old_w)) )
else:
img_new = img.resize( (int(old_w * max_h / old_h), int(max_h)) )
return img_new
|
| getexif() | 打印照片Exif信息from PIL import Image
from PIL.ExifTags import TAGS
img = Image.open(r'test.JPG')
exif = img.getexif()
for k, v in exif.items():
print('{}: {}'.format(TAGS[k], v))
| |
示例
缩放目录所有图片
import os
from PIL import Image
def resize_images_recursive(input_folder, output_folder=None):
if output_folder is None:
output_folder = input_folder + '_1200'
def process_image(input_path, output_path):
try:
with Image.open(input_path) as img:
# 计算新的高度,保持宽高比
width = 1200
ratio = width / float(img.size[0])
height = int(float(img.size[1]) * ratio)
# 只有当原图宽度大于1200时才进行缩放
if img.size[0] > 1200:
resized_img = img.resize((width, height), Image.Resampling.LANCZOS)
resized_img.save(output_path, quality=95)
else:
# 如果原图小于1200px,直接复制
img.save(output_path)
return True
except Exception as e:
print(f"处理图片 {os.path.basename(input_path)} 时出错: {str(e)}")
return False
def process_directory(current_input_dir, current_output_dir):
# 创建对应的输出目录
if not os.path.exists(current_output_dir):
os.makedirs(current_output_dir)
# 遍历当前目录下的所有文件和文件夹
for item in os.listdir(current_input_dir):
input_path = os.path.join(current_input_dir, item)
output_path = os.path.join(current_output_dir, item)
if os.path.isfile(input_path):
# 处理图片文件
if item.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.webp')):
process_image(input_path, output_path)
elif os.path.isdir(input_path):
# 递归处理子文件夹
process_directory(input_path, output_path)
# 开始处理根目录
process_directory(input_folder, output_folder)
print(f"处理完成!输出文件夹: {output_folder}")
# 使用示例
input_folder = r"D:\Download\测试" # 替换为你的输入文件夹路径
resize_images_recursive(input_folder) # 使用默认输出文件夹
# 或者指定输出文件夹
# resize_images(input_folder, "path/to/your/output/folder")
资源
官网
- Pillow 官网:https://python-pillow.org/
- Pillow 文档:https://pillow.readthedocs.io/en/stable/