python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python图片尺寸修改

基于Python编写一个图片批量修改尺寸工具

作者:小庄-Python办公

在日常办公和内容创作中,我们经常需要批量处理大量图片尺寸,今天我要分享一个用Python开发的图片批量修改尺寸工具,它能帮你轻松解决这个问题

前言

在日常办公和内容创作中,我们经常需要批量处理大量图片尺寸。无论是为网站准备素材,还是为报告统一图片规格,手动一张张调整既费时又容易出错。今天我要分享一个用Python开发的图片批量修改尺寸工具,它能帮你轻松解决这个问题。

一、工具功能亮点

这个工具具有以下实用功能:

二、工具核心代码解析

工具基于Python的PyQt5和Pillow库开发,下面是核心代码结构:

import os
from PIL import Image
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QHBoxLayout, QLabel, QPushButton, QListWidget, 
                            QLineEdit, QMessageBox, QFileDialog)

1. 界面布局设计

def init_ui(self):
    # 主窗口设置
    self.setWindowTitle("图片批量修改尺寸工具")
    self.setGeometry(100, 100, 600, 500)
    
    # 主布局
    main_layout = QVBoxLayout()
    
    # 文件夹选择部分
    folder_layout = QHBoxLayout()
    self.label_folder_path = QLabel("请选择图片目录:")
    self.button_choose_folder = QPushButton("选择目录")
    folder_layout.addWidget(self.label_folder_path)
    folder_layout.addWidget(self.button_choose_folder)
    
    # 图片列表
    self.image_list = QListWidget()
    
    # 尺寸输入部分
    size_layout = QHBoxLayout()
    # ...宽度和高度输入框设置...
    
    # 操作按钮
    self.button_resize = QPushButton("批量修改尺寸")
    
    # 将所有部件添加到主布局
    main_layout.addLayout(folder_layout)
    main_layout.addWidget(self.image_list)
    main_layout.addLayout(size_layout)
    main_layout.addWidget(self.button_resize)

2. 核心功能实现

图片尺寸调整函数是工具的核心:

def resize_images(self):
    # 获取用户输入的尺寸
    new_width = int(self.entry_width.text())
    new_height = int(self.entry_height.text())
    
    # 遍历处理每张图片
    for i in range(self.image_list.count()):
        img_name = self.image_list.item(i).text()
        img_path = os.path.join(self.image_folder_path, img_name)
        
        # 使用Pillow打开并调整图片
        with Image.open(img_path) as img:
            resized_img = img.resize((new_width, new_height), Image.Resampling.BICUBIC)
            
            # 根据用户选择保存到备份文件夹或覆盖原文件
            if self.backup_mode:
                backup_path = os.path.join(self.backup_folder_path, img_name)
                resized_img.save(backup_path)
            else:
                resized_img.save(img_path)

三、工具使用教程

1. 准备工作-库的安装

用途安装
PyQt5界面设计pip install PyQt5 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pillow图片处理pip install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple/

2. 使用步骤

运行程序,点击"选择目录"按钮

选取包含需要修改尺寸的图片文件夹

在宽度和高度输入框中输入目标尺寸

点击"批量修改尺寸"按钮

根据需要选择是否创建备份

3. 效果展示

四、实际应用场景

电商运营:批量统一商品图片尺寸

新媒体编辑:为公众号文章准备统一规格的图片

教育培训:标准化教学资料中的插图

个人相册:整理手机拍摄的照片尺寸

五、技术要点总结

PyQt5框架:提供了专业的GUI开发能力

Pillow库:强大的图像处理功能

异常处理:确保程序稳定运行

try:
    # 图片处理代码
except Exception as e:
    QMessageBox.critical(self, "错误", f"处理失败: {str(e)}")

路径处理:使用os.path处理跨平台文件路径

六、扩展思路

这个基础工具还可以进一步扩展:

添加图片质量调整选项

支持按比例缩放而非固定尺寸

增加图片格式转换功能

添加拖放文件支持

实现预设尺寸模板

七、完整代码获取

import os
from PIL import Image
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QLabel, QPushButton, QListWidget, QLineEdit, QScrollArea,
                             QMessageBox, QFileDialog)
from PyQt5.QtCore import Qt


class ImageResizerApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.image_folder_path = ""
        self.backup_folder_path = ""

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("图片批量修改尺寸工具")
        self.setGeometry(100, 100, 600, 500)

        # 主部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)

        # 主布局
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)

        # 文件夹选择部分
        folder_layout = QHBoxLayout()
        self.label_folder_path = QLabel("请选择图片目录:")
        self.button_choose_folder = QPushButton("选择目录")
        self.button_choose_folder.clicked.connect(self.open_directory)

        folder_layout.addWidget(self.label_folder_path)
        folder_layout.addWidget(self.button_choose_folder)
        main_layout.addLayout(folder_layout)

        # 图片列表
        self.image_list = QListWidget()
        main_layout.addWidget(self.image_list)

        # 尺寸输入部分
        size_layout = QHBoxLayout()

        width_layout = QVBoxLayout()
        self.label_width = QLabel("新宽度:")
        self.entry_width = QLineEdit()
        width_layout.addWidget(self.label_width)
        width_layout.addWidget(self.entry_width)

        height_layout = QVBoxLayout()
        self.label_height = QLabel("新高度:")
        self.entry_height = QLineEdit()
        height_layout.addWidget(self.label_height)
        height_layout.addWidget(self.entry_height)

        size_layout.addLayout(width_layout)
        size_layout.addLayout(height_layout)
        main_layout.addLayout(size_layout)

        # 操作按钮
        self.button_resize = QPushButton("批量修改尺寸")
        self.button_resize.clicked.connect(self.resize_images)
        main_layout.addWidget(self.button_resize)

    def open_directory(self):
        """打开并选择一个目录作为图片数据源"""
        folder = QFileDialog.getExistingDirectory(self, "选择图片目录")
        if folder:
            self.image_folder_path = folder
            self.label_folder_path.setText(f"已选择目录: {folder}")
            self.update_image_list()

    def update_image_list(self):
        """更新并显示图片列表"""
        self.image_list.clear()
        if self.image_folder_path:
            for im in os.listdir(self.image_folder_path):
                if im.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
                    self.image_list.addItem(im)

    def create_backup_folder(self):
        """创建备份文件夹"""
        self.backup_folder_path = os.path.join(self.image_folder_path, "resized")
        if not os.path.exists(self.backup_folder_path):
            os.makedirs(self.backup_folder_path)

    def resize_images(self):
        """批量修改图片尺寸"""
        if self.image_list.count() == 0:
            QMessageBox.warning(self, "警告", "没有图片可供调整尺寸!")
            return

        reply = QMessageBox.question(self, "提示", "是否创建备份文件夹?",
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        should_create_backup = reply == QMessageBox.Yes

        if should_create_backup:
            self.create_backup_folder()

        try:
            new_width = int(self.entry_width.text())
            new_height = int(self.entry_height.text())

            if new_width <= 0 or new_height <= 0:
                raise ValueError("宽度和高度必须大于0")

            for i in range(self.image_list.count()):
                im = self.image_list.item(i).text()
                img_path = os.path.join(self.image_folder_path, im)

                with Image.open(img_path) as img:
                    resized_img = img.resize((new_width, new_height), Image.Resampling.BICUBIC)

                    if should_create_backup:
                        backup_img_path = os.path.join(self.backup_folder_path, im)
                        resized_img.save(backup_img_path)
                        print(f"已修改图片 {im} 的尺寸为 {new_width}x{new_height} 并保存到备份文件夹。")
                    else:
                        resized_img.save(img_path)  # 注意:这会覆盖原文件
                        print(f"已修改图片 {im} 的尺寸为 {new_width}x{new_height}")

            QMessageBox.information(self, "完成", "所有图片已按指定尺寸修改完毕!")
        except ValueError as e:
            QMessageBox.critical(self, "错误", str(e))
        except IOError:
            QMessageBox.critical(self, "错误", "无法打开图片文件,请检查文件格式。")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"未知错误: {str(e)}")


if __name__ == "__main__":
    app = QApplication([])
    window = ImageResizerApp()
    window.show()
    app.exec_()

以上就是基于Python编写一个图片批量修改尺寸工具的详细内容,更多关于Python图片尺寸修改的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文