PIL批量压缩图片

2019-11-05  本文已影响0人  Hmcf

人狠话不多,上bug

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
    dirs, suffix = os.path.splitext(infile)
    outfile = '{}-out{}'.format(dirs, suffix)
    return outfile

def compress_image(infile, outfile='', kb=150, step=10, quality=80):
    """不改变图片尺寸压缩到指定大小
    :param infile: 压缩源文件
    :param outfile: 压缩文件保存地址
    :param kb: 压缩目标,KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址,压缩文件大小
    """
    o_size = get_size(infile)
    if o_size <= kb:
        return infile
    outfile = get_outfile(infile, outfile)
    while o_size > kb:
        im = Image.open(infile)
        # 如果出现问题os.error cannot write mode RGBA to JPEG
        # rbgim = im.convert("RGB")  那么需要转换一下
        im.save(outfile, quality=quality)
        if quality - step < 0:
            break
        quality -= step
        o_size = get_size(outfile)
    return outfile, get_size(outfile)

def get_img_path_list(pt):
    file_names = os.listdir(pt)
    file_list = [os.path.join(pt, file) for file in file_names]
    return file_list

if __name__ == '__main__':
    img_list = get_img_path_list("C:\\Users\\THINK\\Pictures\\Saved Pictures")
    for m in img_list:
        compress_image(m)

上一篇下一篇

猜你喜欢

热点阅读