Python's os and Pillow libraries to traverse all subfolders and convert BMP images to PNG format

import os  
from PIL import Image  
  
def convert_bmp_to_png(input_path, output_path):  
    # 遍历所有子文件夹  
    for foldername, subfolders, filenames in os.walk(input_path):  
        # 在子文件夹中遍历所有文件  
        for filename in filenames:  
            # 检查文件是否是BMP格式  
            if filename.endswith('.bmp'):  
                # 打开BMP图片  
                img = Image.open(os.path.join(foldername, filename))  
                # 将图片保存为PNG格式  
                img.save(os.path.join(output_path, filename[:-4] + '.png'))  
  
# 调用函数,将BMP图片转换为PNG格式  
convert_bmp_to_png('input_folder', 'output_folder')

In the above code, input_pathis the path to the input folder and output_pathis the path to the output folder. os.walk()Function is used to iterate through all subfolders and return a list of file names in each subfolder. For each BMP file, use Image.open()a function to open it and img.save()a function to save it in PNG format. When saving a file, use os.path.join()a function to concatenate the file name and the path to the output folder.

Guess you like

Origin blog.csdn.net/MyLovelyJay/article/details/133151489