import PIL.Image as Image
import os
#指定要压缩的文件夹
srcPath = './img'
#压缩后文件夹
dstPath = './ComperssImg'
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/2),int(h/2)),Image.ANTIALIAS) #设置压缩尺寸和选项,注意尺寸要用括号
dImg.save(dstFile) #也可以用srcFile原路径保存,或者更改后缀保存,save这个函数后面可以加压缩编码选项JPEG之类的
print (dstFile+" 成功!")
except Exception:
print(dstFile+"失败!")
python -- 图片压缩处理
最新推荐文章于 2025-09-16 13:57:29 发布
本文介绍了一种使用Python和PIL库批量压缩图片的方法。通过遍历指定文件夹中的所有图片,将它们的尺寸减半并保存到新的文件夹中,有效减少了图片的存储空间。代码实现了自动创建目标目录,并处理了文件读写过程中的异常。

1807

被折叠的 条评论
为什么被折叠?



