# -*- coding: utf-8 -*-
"""
Created on Mon Jun 1 10:28:41 2020
功能:图片压缩
图片大小可以调整
源图片存放目录需要修改
新图片目录没有则建一个,在当前目录下新建
可以压缩整个目录的图片,图片数量无限制
压缩速度还是挺快的。
默认图片格式为.jpg,可以根据实际需要修改
可以运行,2020.6.1
"""
import os
from PIL import Image
import glob
#在程序中设置图片源目录路径,根据实际修改
DIR = r'e:\python\image/'
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)
#
打开原图片压缩
sImg =
Image.open(filename)
w, h =
sImg.size
print(w,
h)
if w <
h:
#如果是直拍,那就用直拍模式
dImg = sImg.resize((2976,
3968), Image.ANTIALIAS) #
设置压缩尺寸和选项,注意尺寸要用括号
else:
#如果是横拍,那就用横拍模式
dImg = sImg.resize((3968,
2976), Image.ANTIALIAS) #
设置压缩尺寸和选项,注意尺寸要用括号
# 像素: 3968
* 2976
#
自己根据图片像素大小调整
#
如果不存在目的目录则创建一个
comdic =
"%s图片压缩后目录/" % 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.save(f2) # save这个函数后面可以加压缩编码选项JPEG之类的
print("%s
压缩成功" % f1[-1])
if __name__ == "__main__":
obj =
Compress_Picture()
obj.compressImage()