图片压缩

导言

最近想做一个相册,图片需要上传到图床然后,调用图床链接进行相册图片显示。为实现图片快速加载,以及节约图床存储空间,写了一个实现图片压缩的小脚本。

所用图床:路过图床

目录结构

1
2
3
4
5
6
7
8
9
$ tree 压缩图片
|-- compress
|-- compressPic.py
|-- finish
`-- prepare
|-- test
| `-- IMG1.JPG
`-- test2
`-- IMG2.JPG

源代码

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
# -*- coding: utf-8 -*-
# @Time : 2021/5/25 14:54
# @Author : SuperBear
# @File : compressPic.py
# @Software: PyCharm

from PIL import Image
import os, shutil

# 图片压缩批处理
def compressImage(srcPath, dstPath):
for filename in os.listdir(srcPath):
# 如果不存在目的目录则创建一个,保持层级结构
if not os.path.exists(dstPath):
os.makedirs(dstPath)
# 拼接完整的文件或文件夹路径
srcFile = os.path.join(srcPath, filename)
dstFile = os.path.join(dstPath, filename)
# 如果是文件就处理
if os.path.isfile(srcFile):
try:
# 打开原图片缩小后保存,可以用if srcFile.endswith(".jpg")或者split,splitext等函数等针对特定文件压缩
sImg = Image.open(srcFile)
w, h = sImg.size
dImg = sImg.resize((int(w / 1.5), int(h / 1.5)), Image.ANTIALIAS) # 设置压缩尺寸和选项,注意尺寸要用括号
dImg.save(dstFile) # 也可以用srcFile原路径保存,或者更改后缀保存,save这个函数后面可以加压缩编码选项JPEG之类的
print(dstPath+ dstFile + " 成功!")
except Exception:
print(dstFile + "失败!")

# 如果是文件夹就递归
if os.path.isdir(srcFile):
# print(srcFile)
compressImage(srcFile, dstFile)


if __name__ == '__main__':
# 遍历压缩图片
compressImage("./prepare", "./compress")
# 移动文件夹prepare到finish
src_path = './prepare/'
target_path = './finish/'
file_list = os.listdir(src_path)
if len(file_list) > 0:
for file in file_list:
shutil.move(src_path + file, target_path + file)

github源代码:https://github.com/sSsuper-Bear/compressPicture/tree/master