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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| from PIL import Image import os import time
def get_size(file): size = os.path.getsize(file) return size / 1024
def get_outfile(infile, outfile): if outfile: return outfile dir, suffix = os.path.splitext(infile) outfile = '{}{}'.format(dir, suffix) print(outfile) return outfile,suffix
def compress_image(infile, outfile='', mb=250, step=10, quality=80): """不改变图片尺寸压缩到指定大小 :param infile: 压缩源文件 :param outfile: 压缩文件保存地址 :param mb: 压缩目标,KB :param step: 每次调整的压缩比率 :param quality: 初始压缩比率 :return: 压缩文件地址,压缩文件大小 """ o_size = get_size(infile) if o_size <= mb: return infile outfile,suffix = get_outfile(infile, outfile) while o_size > mb: im = Image.open(infile) im.save(outfile, quality=quality) if quality - step < 0: break quality -= step o_size = get_size(outfile) return outfile, get_size(outfile)
def resize_image(infile, outfile='', x_s=320): """修改图片尺寸 :param infile: 图片源文件 :param outfile: 重设尺寸文件保存地址 :param x_s: 设置的宽度 :return: """ im = Image.open(infile) x, y = im.size y_s = int(y * x_s / x) out = im.resize((x_s, y_s), Image.ANTIALIAS) outfile = get_outfile(infile, outfile) out.save(outfile)
def listdir(path, list_name): for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path): listdir(file_path, list_name) else: list_name.append(file_path)
if __name__ == '__main__': list = [] listdir('./1/',list) for li in list: compress_image(li)
|