[Python] A simple small program to modify image formats in batches (complete code and program attached)

Program download address: Link: https://pan.baidu.com/s/1ser7iEMRS54syvwl1cck1Q?pwd=jr66 
Extraction code: jr66

1. Complete code

If you want to test the code, remember to make sure you have installed the Python PIL module before using it.

import os
from tkinter import Tk, Button, messagebox
from PIL import Image

# 检查并创建文件夹
def check_and_create_folders():
    if not os.path.exists('Old_Img'):
        os.makedirs('Old_Img')
    if not os.path.exists('New_Img'):
        os.makedirs('New_Img')

# 清空New_Img文件夹
def clear_new_img_folder():
    file_list = os.listdir('New_Img')
    for file_name in file_list:
        file_path = os.path.join('New_Img', file_name)
        if os.path.isfile(file_path):
            os.remove(file_path)

# 图片格式转换函数
def convert_images(image_format):
    old_img_folder = 'Old_Img'
    new_img_folder = 'New_Img'

    # 获取Old_Img文件夹中的图片文件列表
    file_list = os.listdir(old_img_folder)

    for file_name in file_list:
        file_path = os.path.join(old_img_folder, file_name)
        if os.path.isfile(file_path):
            # 打开图片
            image = Image.open(file_path)

            # 构建新的文件名
            new_file_name = os.path.splitext(file_name)[0] + '.' + image_format

            # 保存转换后的图片
            new_file_path = os.path.join(new_img_folder, new_file_name)
            image.save(new_file_path, format=image_format)

    messagebox.showinfo("提示", "转换完成!")

# 创建主窗口
def create_main_window():
    root = Tk()
    root.title("请选择要转换的格式")
    root.geometry('300x200')

    # 清空New_Img文件夹并转换图片
    def convert_btn_click(image_format):
        clear_new_img_folder()
        convert_images(image_format)

    # 创建按钮并绑定事件
    btn_formats = ['jpg', 'png', 'gif']
    for i, format in enumerate(btn_formats):
        btn = Button(root, text=format, command=lambda f=format: convert_btn_click(f))
        btn.place(x=20 + 100 * i, y=80)

    root.mainloop()

# 主程序入口
if __name__ == '__main__':
    check_and_create_folders()
    create_main_window()

2. Usage tutorial

Step 1: Prepare image files: Copy or cut the image files you want to convert to the "Old_Img" folder in the directory where the program is located. Please make sure to only include image files in this folder, other files will be ignored.

Step 2: Run the program: At this time, the program will automatically create a file named "New_Img" to store the converted image

 

Step 3: Select the image format to be converted: After the program is run, a window will pop up with the title "Please select the format to be converted". Several buttons are displayed in the window, corresponding to common image formats (jpg, png and gif).

Step 4: Convert image format: Click the corresponding button to start converting the images in the "Old_Img" folder to the selected format. During the conversion process, the program will clear the "New_Img" folder and save the converted pictures to the "New_Img" folder.

Step 5: Check the conversion results: After the conversion is completed, the program will pop up a prompt box to prompt the user that the conversion is completed. You can open the "New_Img" folder to view the converted image files.

 

Precautions:

  • Please make sure that the "Old_Img" folder only contains the image files you want to convert, other files will be ignored.
  • Please note that the converted image file may overwrite the file with the same name, so it is recommended to back up the original image before converting.
  • This program currently only supports conversion of common image formats. If you need to convert other formats, please modify the code accordingly.

3. Implementation ideas

This code implements a simple image format conversion program, using the tkinterlibrary to create a graphical interface window that allows the user to select the format to convert the image to.

  1. check_and_create_folders()Function is used to check and create folders named "Old_Img" and "New_Img". If these two folders do not exist, use os.makedirs()the function to create them.

  2. clear_new_img_folder()Function to clear the "New_Img" folder. It loops through the list of files in the "New_Img" folder and os.remove()deletes each file using a function.

  3. convert_images(image_format)The function is used to convert the images in the "Old_Img" folder to the specified format. It first gets the list of image files in the "Old_Img" folder, and then does the following for each file:

    • Open the image file and create an Imageobject.
    • Constructs a new filename according to the specified format.
    • Use image.save()the method to save the converted image to the "New_Img" folder and specify the saving format as the specified format.
  4. create_main_window()Function is used to create the main window. It uses Tk()the function to create a rootwindow object named and sets the title of the window to "Please select a format to convert" and the size to 300x200 pixels.

  5. convert_btn_click(image_format)The function is the handler for the button click event. This function is called when the user clicks a button. It first calls clear_new_img_folder()a function to clear the "New_Img" folder, and then calls convert_images(image_format)a function to convert the pictures in the "Old_Img" folder to the specified format.

  6. In create_main_window()the function, Button()three buttons are created using the function, corresponding to three common image formats ("jpg", "png" and "gif"). The text of each button uses the corresponding format name. When the button is clicked, convert_btn_click()the function is called and the corresponding format name is passed as a parameter.

  7. Finally, in the main program entry if __name__ == '__main__':, first call check_and_create_folders()the function to create the folder, and then call create_main_window()the function to create the main window.

Guess you like

Origin blog.csdn.net/zhangawei123/article/details/130920445