Python 壓縮圖片至指定大小

 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('')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章