python3 壓縮圖片到制定大小
阿新 • • 發佈:2020-08-17
code
import base64 import io import os from PIL import Image from PIL import ImageFile # 壓縮圖片檔案 def compress_image(infile,outfile, mb=19, quality=3, k=0.5): """不改變圖片尺寸壓縮到指定大小 :param outfile: 壓縮檔案儲存地址 :param mb: 壓縮目標,KB :param step: 每次調整的壓縮比率 :param quality: 初始壓縮比率 :return: 壓縮檔案地址,壓縮檔案大小""" o_size = os.path.getsize(infile) // 1024 print(o_size, mb) if o_size <= mb: return outfile ImageFile.LOAD_TRUNCATED_IMAGES = True while o_size > mb: im = Image.open(infile) x, y = im.size out = im.resize((int(x*k), int(y*k)), Image.ANTIALIAS)try: out.save(outfile, quality=quality) except Exception as e: print(e) break o_size = os.path.getsize(outfile) // 1024 return outfile pwd=os.getcwd() w_path=os.path.join(pwd,"pic") target=os.path.join(pwd,"chr") for i in os.listdir(w_path):if(not i.startswith(".")): f=os.path.join(w_path,i) tf=os.path.join(target,i) compress_image(f,tf)