Python 批量压缩图片脚本:自动遍历与质量优化
本文介绍一个基于 Python 和 Pillow 库的批量图片压缩脚本。该脚本支持直接拖入文件或文件夹,自动遍历子目录并压缩超过指定大小(默认 4MB)的图片。通过调整 QUALITY 参数(推荐 90),可在保持视觉质量的同时显著减小文件体积,且压缩后文件名和尺寸保持不变。
简介
利用 Python 实现图片的批量压缩,操作方式简便,只需将目标文件夹或具体图片文件直接拖入程序即可执行。
环境依赖
Python 3 运行环境
Pillow 图像处理库(可通过 pip install pillow 命令安装)
使用方法
操作时,将包含图片的文件夹或单张图片直接拖入程序窗口。若拖入的是文件夹,程序会自动递归遍历所有子文件夹,对其中符合格式的图片进行压缩处理。
需注意,压缩后的图片将直接覆盖原文件,文件名和图像尺寸均保持不变,仅调整压缩质量参数以减小文件大小。
代码起始处定义了两个关键变量:
SIZE_CUT = 4,设定为 4,表示仅对文件大小超过 4MB 的图片执行压缩操作。
QUALITY = 90,设定压缩质量为 90。该质量等级下,人眼通常难以察觉画质差异,且能将原本约 10MB 的图片体积压缩近半。若质量值低于 80,画质损失可能较为明显。
代码实现
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# Created by Mario Chen, 01.04.2021, Shenzhen
# My Github site: https://github.com/Mario-Hero
import sys
import os
from PIL import Image
SIZE_CUT = 4 # picture over this size should be compressed. Units: MB
QUALITY = 90 # 90 is good, this number should not be smaller than 80.
def isPic(name):
namelower = name.lower()
return namelower.endswith("jpeg") or namelower.endswith("jpg") or namelower.endswith("png")
def compressImg(file):
#print("The size of", file, "is: ", os.path.getsize(file))
im = Image.open(file)
im.save(file, quality=QUALITY)
def compress(folder):
try:
if os.path.isdir(folder):
print(folder)
file_list = os.listdir(folder)
for file in file_list:
if os.path.isdir(folder+"/"+file):
#print(folder +"/"+ file)
compress(folder +"/"+file)
else:
if isPic(file):
if os.path.getsize(folder + "/" + file) > (SIZE_CUT * 1024 * 1024):
compressImg(folder + "/" + file)
print(file)
else:
if isPic(folder):
if os.path.getsize(folder) > (SIZE_CUT * 1024 * 1024):
compressImg(folder)
except BaseException:
return
if __name__ == '__main__':
for folder in sys.argv:
#print(folder)
compress(folder)
print("Finish.")
#os.system("pause")
实际运行效果

压缩后的文件大小对比

另一种图片压缩实现思路
此方式同样具备自动遍历目录下所有图片的功能。
import os
from PIL import Image
import threading,time
def imgToProgressive(path):
if not path.split('.')[-1:][0] in ['png','jpg','jpeg']: #if path isn't a image file,return
return
if os.path.isdir(path):
return
##########transform img to progressive
img = Image.open(path)
destination = path.split('.')[:-1][0]+'_destination.'+path.split('.')[-1:][0]
try:
print(path.split('\\')[-1:][0],'开始转换图片')
img.save(destination, "JPEG", quality=80, optimize=True, progressive=True) #转换就是直接另存为
print(path.split('\\')[-1:][0],'转换完毕')
except IOError:
PIL.ImageFile.MAXBLOCK = img.size[0] * img.size[1]
img.save(destination, "JPEG", quality=80, optimize=True, progressive=True)
print(path.split('\\')[-1:][0],'转换完毕')
print('开始重命名文件')
os.remove(path)
os.rename(destination,path)
for d,_,fl in os.walk(os.getcwd()): #遍历目录下所有文件
for f in fl:
try:
imgToProgressive(d+'\\'+f)
except:
pass
以上即为 Python 批量压缩图片脚本的详细介绍,如需获取更多相关技术资料,请持续关注本站其他文章。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









