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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
import os from PIL import Image, ExifTags import glob
dir = 'E:/Album Test/public/' patterns = ['*.jpg', "*.png"]
def compressImage(): files = collectFiles(dir, patterns) for f in files: img = doCompress(f)
saveImg(img, f)
def collectFiles(dir, patterns): files = [] for p in patterns: files += (glob.glob('%s%s%s' % (dir, '**\\', p), recursive=True))
for i in range(len(files)): files[i] = files[i].replace('\\', '/')
return files
def doCompress(filename): img = Image.open(filename)
for k in ExifTags.TAGS.keys(): if(ExifTags.TAGS[k] == 'Orientation'): if hasattr(img, '_getexif') and hasattr(img._getexif(), 'items'): exif = dict(img._getexif().items()) if exif[k] == 3: img = img.rotate(180, expand=True) elif exif[k] == 6: img = img.rotate(270, expand=True) elif exif[k] == 8: img = img.rotate(90, expand=True)
w, h = img.size img.thumbnail((2000, 1500), Image.BICUBIC) return img
def saveImg(img, filename): img.save(filename) print(filename, "压缩成功")
if __name__ == "__main__": compressImage()
|