最近买了一批图片,总共一万六千张,600M,占用的空间太大了。但是一张一张使用压缩工具压缩,效率太低了。上网百度了一番,最后借鉴这篇博客Python实现批量压缩图片,略加修改,成功一次性将所有图片压缩到了79.2M。
去python下载,我装的是这个,安装的时候,记得勾选“同时加入环境变量”。
pip install Pillow
新建文件,我命名为“compress.py”。下面,贴上我的代码吧:
# -*- coding: utf-8 -*-
"""
__author__= 'Du'
__creation_time__= '2018/1/5 10:06'
"""
import os
from PIL import Image
from PIL import ImageFile
import glob
import math
ImageFile.LOAD_TRUNCATED_IMAGES = True
# 你要压缩的图片路径
DIR = 'C:/Users/ting/Desktop/test/'
class Compress_Picture(object):
def __init__(self):
# 图片格式,可以换成.bpm等
self.file = '.jpg'
# 图片压缩批处理
def compressImage(self):
for filename in glob.glob('%s%s%s' % (DIR, '*', self.file)):
# print(filename)
# 打开原图片压缩 我的目标图片宽度是150px,高度等比例压缩。用户可根据需要修改宽度
targetWidth = 150
sImg = Image.open(filename)
w, h = sImg.size
rate = round(targetWidth/w,4)
height = math.floor(rate*h)
#print(w,h,rate,height)
dImg = sImg.resize((targetWidth, height), Image.ANTIALIAS) # 设置压缩尺寸和选项,注意尺寸要用括号
# 如果不存在目的目录则创建一个 ,压缩的图片将存储到compress路径下面
comdic = "%scompress/"%DIR
if not os.path.exists(comdic):
os.makedirs(comdic)
# 压缩图片路径名称
f1 = filename.split('/')
f1 = f1[-1].split('\\')
f2 = f1[-1].split('.')
f2 = '%s%s%s'%(comdic, f2[0], self.file)
# print(f2)
dImg.convert("RGB").save(f2) # save这个函数后面可以加压缩编码选项JPEG之类的. PNG 改为“RGBA”
# print("%s compressed succeeded"%f1[-1])
if __name__ == "__main__":
obj = Compress_Picture()
obj.compressImage()
打开命令行,执行“python compress.py”。几秒之内,压缩就完成了。