使用 Python 语言批量改变多个文件夹下的多个图片的尺寸大小

import glob
import os
from PIL import Image

# 1、获取文件夹名称
path = r'H:\wordData\30train'

dirnames = [f for f in os.listdir(path) if os.path.isdir(path + "\\" + f)]
print(dirnames)


def convertSize(jpgfile, outdir, width=112, height=112):  # 将图片的大小的尺寸调整为112*112

    img = Image.open(jpgfile)
    try:
        new_img = img.resize((width, height), Image.BILINEAR)

        if new_img.mode == 'P':
            new_img = new_img.convert("RGB")
        if new_img.mode == 'RGBA':
            new_img = new_img.convert("RGB")

        new_img.save(os.path.join(outdir, os.path.basename(jpgfile)))
    except Exception as e:
        print(e)


# 2、遍历文件夹
for dir_name in dirnames:
    dir_path = path + "\\" + dir_name

    # 3、创建新文件夹
    target_path = r"H:\wordData\new_30train" + "\\" + dir_name + "\\"
    if not os.path.exists(target_path):
        os.makedirs(target_path)

    # 4、遍历文件夹中的图片, 修改尺寸
    for pic in os.listdir(dir_path):  # 修改该文件夹下的图片
        convertSize(dir_path + "\\" + pic, target_path)  # 另存为的文件夹路径
    print(dir_path + "文件夹下的图片处理完毕.\n")

print("全部文件夹下的图片处理完毕.")

由于代码

new_img = img.resize((width, height), Image.BILINEAR)

参数 Image.BILINEAR 将被弃用,所以会报警告,不过不影响,在使用时可不加该参数。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xuechanba

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值