指定文件夹下批量修改图片文件名并修改图片文件格式

代码展示:

import os
from PIL import Image
source_dir = r'sources_multiformats'
destination_dir = r'destinations_monoformat'

r'''
在当前目录下有两个文件夹,分别是source_dir和destination_dir,
将source_dir目录下的所有jpg、png、bmp图片,并且灰度图转为RGB格式
转为jpg格式后保存到destination_dir文件夹下,
同时去除文件名中的空格.
'''

if __name__ == '__main__':
    des_imgs = os.listdir(source_dir)
    # print(des_imgs)
    # print(len(des_imgs))
    for img_path in des_imgs:
        if img_path.endswith('.jpg') or img_path.endswith('.bmp') or img_path.endswith('.png'):
            new_img_path = os.path.join(destination_dir,img_path.replace(' ','')[:-4]+'.jpg')
            # print(img_path,'--->',new_img_path)
            img = Image.open(os.path.join(source_dir,img_path)).convert('RGB') 
            img.save(new_img_path)

控制台下输出结果展示:

Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。

尝试新的跨平台 PowerShell https://aka.ms/pscore6

加载个人及系统配置文件用了 940 毫秒。
(base) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments> conda activate pytorch_1.7.1_cu102
(pytorch_1.7.1_cu102) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments>  & 'D:\Anaconda3\envs\pytorch_1.7.1_cu102\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2021.1.502429796\pythonFiles\lib\python\debugpy\launcher' '54118' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\my-experiments\图片改名字并改格式.py'
(pytorch_1.7.1_cu102) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments>

程序运行结果截图:

在这里插入图片描述

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值