python --批量转图片格式

单次转换

from PIL import Image


img = Image.open(r'C:\Users\EDY\Desktop\20220531203949.bmp')
img.save(r'C:\Users\EDY\Desktop\20220531203949.png')

批量转换

import os
from PIL import Image


class ImageToFormat(object):
    '''批量转图片格式'''

    def __init__(self, source_path: str, target_path: str, *, target_suffix='png'):
        """
        source_path: 需要转化的文件夹路径(程序会递归遍历当前路径下所有图片);
        target_path: 目标文件路径,会在目标路径下新建一个文件夹,并复制原始文件夹结构;
        target_suffix: 需要转换的图片后缀;
        """
        self._source_path = source_path
        self._target_path = target_path
        self._target_suffix = target_suffix

    @staticmethod
    def save_single(root: str, source_filename: str, suffix: str, target_path: str, target_suffix: str):
        try:
            img = Image.open(os.path.join(root, source_filename + suffix))
            img = img.convert('RGB')
            img.save(os.path.join(target_path, f'{source_filename}.{target_suffix}'), target_suffix)
        except Exception as e:
            print(e)
            return e
        return False

    @staticmethod
    def copy_single(root: str, source_filename: str, target_path: str):
        try:
            with open(os.path.join(root, source_filename), 'rb') as file:
                read = file.read()
            with open(os.path.join(target_path, source_filename), 'wb') as file:
                file.write(read)
        except Exception as e:
            print(e)
            return e
        return False

    def run(self):
        file_paths = []
        source_path_len = len(self._source_path)

        if not (self._source_path.endswith('/') or self._source_path.endswith('\\')):
            source_path_len += 1

        if not os.path.exists(self._target_path):
            os.makedirs(self._target_path)

        for root, directories, files in os.walk(self._source_path):

            for file in files:
                path = root[source_path_len:]  # 去掉要被替换掉的目录前缀
                target_directory = os.path.join(self._target_path, path)  # 这是新目录,要保存的位置
                file_paths.append((root, file, target_directory))

            for directory in directories:  # 创建目录,要是把所有文件保存在同目录下,同名文件会冲突
                source_path = os.path.join(root, directory)
                path = source_path[source_path_len:]
                target_directory = os.path.join(self._target_path, path)

                if not os.path.exists(target_directory):
                    os.makedirs(target_directory)

        for root, file, target in file_paths:
            fname, suffix = os.path.splitext(file)
            lower_suffix = suffix.lower()

            if lower_suffix in ('.jpg', '.jpeg', '.bmp', '.png'):
                ImageToFormat.save_single(root, fname, suffix, target, self._target_suffix)

            else:
                ImageToFormat.copy_single(root, file, target)


r = ImageToFormat(r'D:\yi\game_resources\media', r'C:\Users\EDY\Desktop\新建文件夹1', target_suffix='bmp')
r.run()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

像风一样的男人@

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

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

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

打赏作者

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

抵扣说明:

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

余额充值