1 import base64
2 import io
3 import os
4 from PIL import Image
5 from PIL import ImageFile
6
7
8 # 压缩图片文件
9 def compress_image(outfile, mb=600, quality=85, k=0.9):
10 """不改变图片尺寸压缩到指定大小
11 :param outfile: 压缩文件保存地址
12 :param mb: 压缩目标,KB
13 :param step: 每次调整的压缩比率
14 :param quality: 初始压缩比率
15 :return: 压缩文件地址,压缩文件大小
16 """
17
18 o_size = os.path.getsize(outfile) // 1024
19 print(o_size, mb)
20 if o_size <= mb:
21 return outfile
22
23 ImageFile.LOAD_TRUNCATED_IMAGES = True
24 while o_size > mb:
25 im = Image.open(outfile)
26 x, y = im.size
27 out = im.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
28 try:
29 out.save(outfile, quality=quality)
30 except Exception as e:
31 print(e)
32 break
33 o_size = os.path.getsize(outfile) // 1024
34 return outfile
35
36
37 # 压缩base64的图片
38 def compress_image_bs4(b64, mb=190, k=0.9):
39 """不改变图片尺寸压缩到指定大小
40 :param outfile: 压缩文件保存地址
41 :param mb: 压缩目标,KB
42 :param step: 每次调整的压缩比率
43 :param quality: 初始压缩比率
44 :return: 压缩文件地址,压缩文件大小
45 """
46 f = base64.b64decode(b64)
47 with io.BytesIO(f) as im:
48 o_size = len(im.getvalue()) // 1024
49 if o_size <= mb:
50 return b64
51 im_out = im
52 while o_size > mb:
53 img = Image.open(im_out)
54 x, y = img.size
55 out = img.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
56 im_out.close()
57 im_out = io.BytesIO()
58 out.save(im_out, 'jpeg')
59 o_size = len(im_out.getvalue()) // 1024
60 b64 = base64.b64encode(im_out.getvalue())
61 im_out.close()
62 return str(b64, encoding='utf8')
63
64
65 if __name__ == "__main__":
66 for img in os.listdir('./out_img'):
67 compress_image(outfile='./out_img/' + str(img)[0:-4] + '.png')
68 print('完')