方法一 直接调整宽高
先放参考资料:如何用Python智能批量压缩图片?
import math
from glob import glob
from PIL import Image
import os
def resize_images(source_dir, target_dir, threshold):
filenames = glob('{}/*'.format(source_dir))
if not os.path.exists(target_dir):
os.makedirs(target_dir)
for filename in filenames:
filesize = os.path.getsize(filename)
print(filename+":"+str(filesize))
if filesize >= threshold:
print(filename)
with Image.open(filename) as im:
width, height = im.size
new_width = int(threshold / filesize * width)
new_height = int(threshold / filesize * height)
resized_im = im.resize((new_width, new_height))
output_filename = filename.replace(source_dir, target_dir)
resized_im.save(output_filename)
source_dir = r"D:\图片"
target_dir = r"D:\压缩后的图片"
threshold = 200*1024 #限制在200k
resize_images(source_dir, target_dir, threshold)
方法二 通过tinify压缩
再放参考资料: 10 行 Python 代码,批量压缩图片 500 张,简直太强大了
import tinify
import os
tinify.key = '获取的key'
path = r"D:\图片" # 图片存放的路径
for dirpath, dirs, files in os.walk(path):
for file in files:
imgpath = os.path.join(dirpath, file)
print("compressing ..."+ imgpath)
tinify.from_file(imgpath).to_file(imgpath)