知行迭代
导航
首页
最近更改
随机页面
常用
分类目录
Linux命令
Mediawiki常用
电脑技巧
工具
链入页面
相关更改
特殊页面
页面信息
登录
查看“Pillow”的源代码
←
Pillow
页面
讨论
阅读
查看源代码
查看历史
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:[
[1]
]
您可以查看和复制此页面的源代码。
Pillow是一个[[Python]]的图像处理库,PIL(Python Imaging Library)2011年停止更新,随后Pillow分支了PIL并添加了Python 3的支持,现在成为PIL的替代品。 ==简介== ===时间轴=== ===安装=== 使用[[pip]]安装: <syntaxhighlight lang="bash" > pip install --upgrade pip pip install --upgrade Pillow </syntaxhighlight> {{了解更多 |[https://pillow.readthedocs.io/en/stable/installation.html Pillow 文档:安装] }} ==快速入门== ===图片格式转换=== <syntaxhighlight lang="python" > from PIL import Image im = Image.open("test.webp") print(im.size, im.format) # 打印图片尺寸,格式 im.show() # 显示图片 im.save("test.jpg") </syntaxhighlight> {{了解更多 |[https://pillow.readthedocs.io/en/stable/handbook/tutorial.html Pillow 文档:Image类的使用] }} ==Image类== ===生成Image类=== {| class="wikitable" ! 名称 ! 描述 ! 示例 |- | [https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open open()] |从图像文件生成Image对象 <br /><br /><code>PIL.Image.open(fp, mode='r', formats=None)</code> | <syntaxhighlight lang="python" > from PIL import Image im = Image.open("test.jpg") </syntaxhighlight> |- | [https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.new new()] | 生成一个新的Image对象 <br /><br /><code>PIL.Image.new(mode, size, color=0)</code> | <code>im_new = Image.new('RGB',(1200,1200), 'white')</code> |- | [https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.frombytes frombytes()] | | |} {{了解更多 |[https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image Pillow 文档:The Image Class] |[https://pillow.readthedocs.io/en/stable/handbook/tutorial.html#more-on-reading-images Pillow 文档:详细了解如何读取图片] }} ===属性=== 以下示例使用如下代码: <syntaxhighlight lang="python" > from PIL import Image im = Image.open("test.jpg") print(im.format) </syntaxhighlight> {| class="wikitable" ! 名称 ! 描述 ! 示例 |- | filename | 文件名 | |- | format | 文件格式 | <code>im.format</code> 返回'jpg' |- | size | | |- | | | |} {{了解更多 |[https://pillow.readthedocs.io/en/stable/reference/Image.html#image-attributes Pillow 文档:Image属性] }} ===方法=== {| class="wikitable" ! 名称 ! 描述 ! 示例 |- | save() | 保存图片。 | |- | crop() | 裁剪图片。 输入参数4元组,坐标为(左、上、右、 下),其中 (0, 0) 中的 左上角,数值为像素。 | <syntaxhighlight lang="python" > box = (100, 100, 400, 400) region = im.crop(box) </syntaxhighlight> 先使用rembg抠图,再裁剪掉多余的边。透明度通道0为透明,255为不透明,计算分别行和列,不为0的起始和终止坐标即可切割。 <syntaxhighlight lang="python" > 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)) </syntaxhighlight> |- | resize() | 调整图片大小。 | <code>im.resize( (200,500) )</code>,调整图片尺寸为200x500。<br /> 自定义一个调整大小函数 <syntaxhighlight lang="python" > 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 </syntaxhighlight> |- | | | |- | | | |- | getexif() | | 打印照片Exif信息<syntaxhighlight lang="python" > 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)) </syntaxhighlight> |- | | | |- | | | |} {{了解更多 |[https://pillow.readthedocs.io/en/stable/handbook/tutorial.html * Pillow 文档:教程] |[https://pillow.readthedocs.io/en/stable/reference/Image.html#the-image-class Pillow API:The Image Class] }} ==示例== ===缩放目录所有图片=== <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> ==资源== ===官网=== * Pillow 官网:https://python-pillow.org/ * Pillow 文档:https://pillow.readthedocs.io/en/stable/ ===网站===
本页使用的模板:
模板:了解更多
(
查看源代码
)
返回至“
Pillow
”。