項目中大量用到圖片加載,因爲圖片太大,加載速度很慢,所以須要對文件進行統一壓縮spa
from PIL import Image import os
def get_size(file): # 獲取文件大小:KB size = os.path.getsize(file) return size / 1024
def get_outfile(infile, outfile): if outfile: return outfile dir, suffix = os.path.splitext(infile) outfile = '{}-out{}'.format(dir, suffix) return outfile
def compress_image(infile, outfile='', mb=150, 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 = 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=1376): """修改圖片尺寸 :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) if __name__ == '__main__': compress_image(r'D:\learn\space.jpg') resize_image(r'D:\learn\space.jpg')