批量缩小图片脚本

包是pillow. 限制图片的短边像素数,长边等比缩小。所有图片放入一个目录,运行,输入该目录即可。


from PIL import Image
import os
import pathlib

Image.MAX_IMAGE_PIXELS = 2800000000  #增大pillow的像素限制

path = input('请输入路径:')
if not os.path.exists(path):
    print('路径不存在!')
else:
    leng = input('请输入最小边宽度:')
    dirlist = os.walk(path)
    new_path = os.path.dirname(path) + "/new/" # new文件夹存放转换后的图片,保留原图。
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    for root,dirs,files in dirlist:
        for f in files:
            full_path = os.path.join(root,f)
            p = pathlib.Path(full_path)
            image = Image.open(full_path)
            width = image.width
            height = image.height
            if width < height:
                if width > int(leng):
                    t_height = int(image.height*(int(leng)/image.width))
                    resized_image = image.resize((int(leng), t_height))
                else:
                    resized_image = image #未缩放的图片也放入新目录
                    #continue
            elif width > height:
                if height > int(leng):
                    t_width = int(image.width * (int(leng)/image.height))
                    resized_image = image.resize((t_width, int(leng)))
                else:
                    resized_image = image
                    #continue
            resized_image.save(new_path + p.name)
            

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值