Recently, I need to compress a batch of pictures in batches. At this time, the first thing that comes to my mind is whether python can help me complete this problem. I searched for online tutorials and found that there are really some. I will summarize and share with you. If you don’t understand something, you can leave a message to communicate.
import os
from PIL import Image
def compress_images(input_folder, output_folder, target_size):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.endswith(".jpg") or filename.endswith(".png"):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)
img = Image.open(input_path)
# 保持原尺寸
img.thumbnail((600, 338))
# 逐渐降低质量直到满足目标大小
img.save(output_path, optimize=True, quality=95)
while os.path.getsize(output_path) > target_size*1000:
img.save(output_path, optimize=True, quality=95)
print(f"Compressed {filename} to {os.path.getsize(output_path)//1000}KB")
input_folder = "images" # 输入文件夹路径
output_folder = "new_images" # 输出文件夹路径
target_size = 500 # 目标大小(KB)
compress_images(input_folder, output_folder, target_size)
8.8G before compression, less than 600M after compression, the efficiency is relatively high