Python实用小工具,图片批量转换,解决了UI小姐姐的工作烦恼

嘿嘿,最近收到了一位UI小妹妹的求助,她总是抱怨每次做出的设计图一会要转成 PNG,一会又要转成 JPG,格式来回转换,真是烦不胜烦。想要花姐帮她解决这个问题?当然可以!💡

今天就给大家分享下如何实现这款小工具,不仅能快速批量转换图片格式,还能根据需要重新命名图片文件,程序超简单,界面友好,UI小妹妹都能轻松上手。🤩

废话不多说,马上来看看这个工具怎么做的吧!

1. 需求分析:你需要一个什么样的工具?

首先,我们明确一下工具的功能需求:

  • 选择要转换的图片文件夹:用户可以选择一个文件夹,里面有很多图片需要转换格式。
  • 选择目标格式:用户可以选择转换成的目标格式,比如 PNG、JPG、BMP、GIF 等等。
  • 选择命名方式:转换后的图片文件可以使用原文件名,或者根据数字重新编号命名。
  • 进度条显示:转换过程中显示进度条,方便用户了解当前转换的状态。

并且,转换后的图片将存放在原文件夹下自动新建的 converted_images 文件夹中,省去了手动选择保存路径的麻烦。🎉

2. 工具的设计与实现:Python + wxPython + PIL

这次的工具,我们用了两个库:

  • Pillow(PIL):用于处理图片格式的转换。
  • wxPython:用于构建图形界面,让这个工具更直观易用。

2.0 项目目录结构

bash 复制代码
image_converter/
│
├── converter/
│   ├── __init__.py
│   ├── converter.py  # 包含图像转换的类
│
├── ui/
│   ├── __init__.py
│   ├── ui.py  # 包含GUI界面的类
│
├── main.py  # 主程序入口
└── requirements.txt  # 项目依赖

2.1 编写图片转换功能(核心部分)

首先,我们写一个 ImageConverter 类来完成图片的转换任务。这个类的主要职责就是:

  • 遍历文件夹中的所有图片
  • 将每张图片转换成目标格式
  • 支持两种命名方式:保持原文件名或按编号重新命名。
python 复制代码
import os
from PIL import Image

class ImageConverter:
    def __init__(self, folder, target_format, rename_method):
        self.folder = folder
        self.target_format = target_format
        self.rename_method = rename_method
        self.output_folder = os.path.join(self.folder, "converted_images")

        # 如果output文件夹不存在,创建一个新的
        if not os.path.exists(self.output_folder):
            os.makedirs(self.output_folder)

    def convert_images(self, progress_callback=None):
        files = [f for f in os.listdir(self.folder) if f.lower().endswith(('jpg', 'jpeg', 'png', 'bmp', 'gif', 'tiff'))]
        
        if not files:
            raise ValueError('该文件夹没有符合要求的图片!')

        counter = 1
        for file in files:
            input_path = os.path.join(self.folder, file)
            output_name = f"image_{counter}.{self.target_format}" if self.rename_method == "按编号重命名" else file
            output_path = os.path.join(self.output_folder, output_name)

            try:
                with Image.open(input_path) as img:
                    img.convert("RGB").save(output_path, self.target_format.upper())
                if progress_callback:
                    progress_callback(counter / len(files) * 100)  # 更新进度条
                counter += 1
            except Exception as e:
                raise ValueError(f"转换失败:{e}")

        return True

这里,我们对每张图片都进行了格式转换,并在转换的过程中更新了进度条。最重要的一点是,我们在原文件夹里自动创建了一个 converted_images 文件夹来存放转换后的图片,这样就不会搞乱文件结构了。

2.2 构建图形界面(让操作更直观)

接下来,使用 wxPython 来创建一个图形界面,用户可以通过按钮选择文件夹、选择目标格式、选择命名方式,并看到转换进度。

python 复制代码
import wx
from converter.converter import ImageConverter

class ImageConverterUI(wx.Frame):
    def __init__(self, *args, **kw):
        super(ImageConverterUI, self).__init__(*args, **kw)

        self.panel = wx.Panel(self)

        # 标签和选择文件夹控件
        self.folder_label = wx.StaticText(self.panel, label="选择图片文件夹", pos=(10, 10))
        self.folder_picker = wx.DirPickerCtrl(self.panel, pos=(150, 10), size=(300, 30))

        # 目标格式标签和下拉菜单
        self.format_label = wx.StaticText(self.panel, label="选择目标格式", pos=(10, 50))
        self.format_choice = wx.Choice(self.panel, pos=(150, 50), choices=["PNG", "JPG", "BMP", "GIF", "TIFF"], size=(100, 30))

        # 命名方式标签和下拉菜单
        self.rename_label = wx.StaticText(self.panel, label="选择命名方式", pos=(10, 90))
        self.rename_choice = wx.Choice(self.panel, pos=(150, 90), choices=["原文件名", "按编号重命名"], size=(100, 30))

        # 进度条
        self.progress_bar = wx.Gauge(self.panel, range=100, pos=(10, 130), size=(440, 30))

        # 提交按钮
        self.submit_button = wx.Button(self.panel, label="转换", pos=(10, 170))
        self.submit_button.Bind(wx.EVT_BUTTON, self.on_convert)

        self.SetSize((480, 250))
        self.SetTitle("图片格式转换工具")

    def on_convert(self, event):
        folder = self.folder_picker.GetPath()
        target_format = self.format_choice.GetStringSelection().lower()
        rename_method = self.rename_choice.GetStringSelection()

        if not folder or not target_format:
            wx.MessageBox('请选择文件夹和目标格式!', '错误', wx.ICON_ERROR)
            return

        self.convert_images(folder, target_format, rename_method)

    def convert_images(self, folder, target_format, rename_method):
        try:
            converter = ImageConverter(folder, target_format, rename_method)
            converter.convert_images(progress_callback=self.update_progress)
            wx.MessageBox('转换完成!', '成功', wx.ICON_INFORMATION)
        except ValueError as e:
            wx.MessageBox(str(e), '错误', wx.ICON_ERROR)

    def update_progress(self, progress):
        # 确保进度条的值是整数
        self.progress_bar.SetValue(int(progress))

2.3 主程序入口

最后,我们的主程序文件 main.py 就是简单的启动程序和显示界面:

python 复制代码
import wx
from ui.ui import ImageConverterUI

def main():
    app = wx.App(False)
    frame = ImageConverterUI(None)
    frame.Show()
    app.MainLoop()

if __name__ == "__main__":
    main()

3. 使用步骤:让工具变得简单

  1. 安装依赖 :在项目根目录下创建一个 requirements.txt 文件并写入以下内容:
txt 复制代码
pillow
wxPython

然后安装依赖:

bash 复制代码
pip install -r requirements.txt
  1. 运行程序:在命令行中运行主程序:
bash 复制代码
python main.py
  1. 操作界面 :运行程序后,会弹出一个简单的界面。你只需要:
    • 选择你要转换的图片文件夹
    • 选择目标图片格式(PNG、JPG 等)
    • 选择命名方式(保留原文件名或按编号重命名)
    • 点击"转换"按钮

转换后的图片会自动存放在文件夹中创建的 converted_images 文件夹里,转换过程中的进度会在进度条中显示。

就这样,我们通过 Python、Pillow 和 wxPython 写了一个简单易用的图片格式转换工具,解决了UI小妹妹每次格式转换的烦恼。😄

4. 小作业

之前花姐讲过如何把Python打包成exe,小伙伴们不妨自己动手尝试下,做好的记得举手🙋告诉花姐!

同时大家可以根据自己的需求,进一步扩展这个工具,比如支持嵌套文件夹等等......

希望这篇文章对你有帮助,如果你有任何问题,或者想要和花姐一起聊聊 Python,欢迎留言哦!🚀

相关推荐
锅巴胸7 分钟前
基于 Milvus 和 BiomedBERT 的医学文献智能搜索系统
python·milvus
uhakadotcom7 分钟前
WebAssembly反爬虫技术:隐藏核心逻辑和加密数据
后端·面试·github
JINX的诅咒27 分钟前
定点除法器设计与实现:从基础算法到数值优化
笔记·python·算法·架构
MingDong52330 分钟前
如何在IPhone 16Pro上运行python文件?
python
无眠_32 分钟前
Spring Boot Bean 的生命周期管理:从创建到销毁
java·spring boot·后端
钢铁男儿35 分钟前
Python Django入门(建立项目)
python·django·sqlite
摩尔曼斯克的海1 小时前
YOLO数据集分割训练集、测试集和验证集
图像处理·python·yolo
Y1nhl2 小时前
搜广推校招面经五十五
人工智能·python·深度学习·机器学习·广告算法·推荐算法·搜索算法
z26373056113 小时前
springboot继承使用mybatis-plus举例相关配置,包括分页插件以及封装分页类
spring boot·后端·mybatis
老大白菜4 小时前
lunar是一款无第三方依赖的公历 python调用
前端·python