python压缩照片

#pip install Pillow

from PIL import Image
import os
import shutil

input_folder = ‘D:\Camera’ # 输入文件夹
output_quality = 80 # 输出图片质量

备份目录

backup_folder = input_folder + ‘_bak’
shutil.copytree(input_folder, backup_folder)

遍历输入文件夹及子文件夹

for root, dirs, files in os.walk(input_folder):
for file_name in files:
if file_name.endswith(‘.jpg’) or file_name.endswith(‘.jpeg’) or file_name.endswith(‘.png’):
input_file = os.path.join(root, file_name)
output_file = os.path.join(root, file_name)

        # 打开图片并获取宽高
        image = Image.open(input_file)
        width, height = image.size
        print(f'处理图片: {input_file}')

        # 判断宽度大于高度且宽度大于1920
        if width > height and width > 1920:
            # 调整宽度为1920,高度按比例缩放
            new_width = 1920
            new_height = int(height * new_width / width)
            image.thumbnail((new_width, new_height))
            print(f'调整宽度为: {new_width}, 高度为: {new_height}')

        # 判断高度大于宽度且高度大于1920
        elif height > width and height > 1920:
            # 调整高度为1920,宽度按比例缩放
            new_height = 1920
            new_width = int(width * new_height / height)
            image.thumbnail((new_width, new_height))
            print(f'调整高度为: {new_height}, 宽度为: {new_width}')

        # 转换为JPEG格式并保存
        image = image.convert('RGB')
        image.save(output_file, 'JPEG', quality=output_quality)
        print(f'保存图片到: {output_file}')
        print('-' * 20)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值