前言

    今天迁移文件,需要对大量的图片进行压缩,用PS一张一张的处理效率特别低,而网上的在线工具批量处理几乎都是收费的,所以干脆用python脚本来处理,一劳永逸,以后也方便自己使用。

安装PIL图像处理库

PIL是一个Python图像处理库,PillowPIL的一个很友好的分支,所以,我们可以通过安装Pillow来使用PIL。文档:pillow官网

我使用的是mac电脑,以下命令在mac上执行。

1,安装pip工具,如果已经安装,跳过

1
sudo easy_install pip

2,安装Pillow,借助pip工具安装起来也很简单

1
pip install Pillow

压缩代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
#!coding=utf-8
#author=guolin
#依赖:pip install Pillow
from PIL import Image
import os
import tkinter as tk
from tkinter import filedialog

# 尺寸比例
size_ratio = 0.7
# 压缩质量
quality = 70

# 遍历文件夹压缩
def batch_compress(srcPath, distPath):

# 遍历文件夹
for filename in os.listdir(srcPath):
# 目录验证
if not os.path.exists(distPath):
os.makedirs(distPath)

# 拼接完整的文件或文件夹路径
srcFile = os.path.join(srcPath, filename)
distFile = os.path.join(distPath, filename)

# 如果是文件 就调用压缩
if os.path.isfile(srcFile):
if(is_image(srcFile)):
# 执行压缩操作
compression(srcFile,distFile)
else:
print (distFile + " 文件不是图片,跳过!")
# 如果是文件夹 就继续递归
elif os.path.isdir(srcFile):
batch_compress(srcFile, distFile)

# 文件是否为图片判断
def is_image(srcFile):
if (srcFile.lower().endswith(('.bmp', '.dib','.gif', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff'))):
return True
else:
return False

# 压缩图片并保存
def compression(srcFile,distFile):
try:
# 读取原图
srcImg = Image.open(srcFile)
w, h = srcImg.size
# 重新设置图片尺寸和选项,Image.ANTIALIAS:平滑抗锯齿
distImg = srcImg.resize((int(w * size_ratio), int(h * size_ratio)), Image.ANTIALIAS)
# 保存为新图
distImg.save(distFile, quality=quality)
print (distFile + " 压缩成功!")
except Exception as e:
print (distFile + " 压缩失败!异常信息:", e)

def chooseDir():
root = tk.Tk()
root.withdraw()
choose_dir_path = filedialog.askdirectory()
if choose_dir_path is None or len(choose_dir_path) <= 0:
print('没有任何选择,程序退出!')
exit()
print('您选择的目录:', choose_dir_path)
return choose_dir_path

if __name__ == '__main__':
print ("=================开始执行=================")
# 指定图片目录以及压缩后的图片目录
choose_dir_path = chooseDir()
batch_compress(choose_dir_path, choose_dir_path + "/dist")
print ("=================执行结束=================")
print ("压缩后的图片已经保存到:" + choose_dir_path + "/dist")