方法一 直接調整寬高
先放參考資料:如何用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)