批量处理图片大小

2024-06-07 11:00:00   技术   python PIL 街景

最近在整理旧照片,有的上传到了街景相册。

感兴趣的可以:

:camera:2016年街拍 :camera:2017年街拍 :camera:2018年街拍

:camera:2019年街拍 :camera:2020年街拍 :camera:2021年街拍

:camera:2022年街拍 :camera:2023年街拍 :camera:2024年街拍

本身没有什么技术含量,只是找个地方放下代码。

import os
import glob
from PIL import Image


def resize_image(image_path, output_path):
    with Image.open(image_path) as image:
        width, height = image.size
        if width > height:
            target_width = 800
            target_height = int(height / width * 800)
        else:
            target_height = 800
            target_width = int(width / height * 800)
        resized_image = image.resize((target_width, target_height))
        resized_image.save(output_path)
        print(image_path)


folder_path = "."
result_folder_path = "results"
if not os.path.exists(result_folder_path):
    os.makedirs(result_folder_path)
image_formats = ['*.jpg', '*.jpeg', '*.png', '*.gif']
image_list = []
for image_format in image_formats:
    image_list.extend(glob.glob(os.path.join(folder_path, image_format)))
for image_path in image_list:
    resize_image(image_path, os.path.join(result_folder_path, image_path))
评论共