栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

使用Python批量转换图片格式

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Python批量转换图片格式

PNG 创建于 1995 年,是用于在网络上传输图像的 GIF 格式的免费替代品。因为PNG没专利,所以编辑和查看PNG也不需要许可。PNG图像在压缩时不会丢失任何数据,编码、解码方式一样。与JPEG 文件等有损选项相比,这是一个很大的优势。

所以,要想把其它格式的图片转换为PNG格式是很方便的。除了一种情况,那就是图片比较多的时候。这时需要一些工具来帮助我们批量转换。很多解决方案都需要安装什么软件,下面这种,额……也需要安装脚本解释器,除此之外还得安装一个包:

pip install pillow

然后编写和执行脚本:

from multiprocessing import Pool
import os
import re
from PIL import Image


def save_single(
    root: str, source_filename: str, suffix: str, target_path: str, target_suffix: str='png'
):
    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


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(source_path: str, target_path: str, pool):
    file_paths = []
    source_path_len = len(source_path)
    if not(source_path.endswith('/') or source_path.endswith('\')):
        source_path_len += 1
    if not os.path.exists(target_path):
        os.makedirs(target_path)
    for root, directories, files in os.walk(source_path):
        for file in files:
            path = root[source_path_len:] # 去掉要被替换掉的目录前缀
            target_directory = os.path.join(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(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'):
            pool.apply_async(save_single, (root, fname, suffix, target))
        else:
            pool.apply_async(copy_single, (root, file, target))


SOURCE_PATH = '/home/ubuntu/example/Download' # 一个目录,脚本会递归地访问这文件夹里的图片
TARGET_PATH = '/home/ubuntu/example/project/assets' # 脚本会在转换的时候把原来目录的结构都复刻进来,也就是说转换前后各个图片的相对位置没变

if __name__ == "__main__":
    pool = Pool(8) # 这个8是进程池的大小,根据电脑核数和内存以及磁盘转速来选
    run(SOURCE_PATH, TARGET_PATH, pool)
    pool.close()
    pool.join()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857376.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号