当前位置: 代码网 > it编程>前端脚本>Python > 使用Python实现图片处理工具

使用Python实现图片处理工具

2025年01月11日 Python 我要评论
本文将详细分析一款基于wxpython和pillow (pil)的简单图片处理工具,包括核心功能的实现与代码的设计思路。这款工具支持图片选择、旋转、合并、压缩,并且具有友好的图形用户界面(gui)。全

本文将详细分析一款基于 wxpython 和 pillow (pil) 的简单图片处理工具,包括核心功能的实现与代码的设计思路。这款工具支持图片选择、旋转、合并、压缩,并且具有友好的图形用户界面(gui)。

全部代码

import wx
from pil import image
import os
from io import bytesio

class imageprocessorframe(wx.frame):
    def __init__(self):
        super().__init__(parent=none, title='图片处理工具')
        self.selected_images = []
        self.current_image = none
        self.current_pil_image = none  # 存储pil image对象
        self.init_ui()
        
    def init_ui(self):
        panel = wx.panel(self)
        main_sizer = wx.boxsizer(wx.horizontal)
        
        # 左侧控制面板
        left_sizer = wx.boxsizer(wx.vertical)
        
        # 创建按钮
        select_btn = wx.button(panel, label='选择图片')
        rotate_btn = wx.button(panel, label='旋转')
        merge_btn = wx.button(panel, label='合并')
        compress_btn = wx.button(panel, label='压缩')
        
        # 创建列表框显示选择的图片
        self.list_box = wx.listbox(panel, size=(200, 300))
        
        # 添加组件到左侧sizer
        left_sizer.add(select_btn, 0, wx.all | wx.expand, 5)
        left_sizer.add(self.list_box, 1, wx.all | wx.expand, 5)
        left_sizer.add(rotate_btn, 0, wx.all | wx.expand, 5)
        left_sizer.add(merge_btn, 0, wx.all | wx.expand, 5)
        left_sizer.add(compress_btn, 0, wx.all | wx.expand, 5)
        
        # 右侧图片显示区域
        right_sizer = wx.boxsizer(wx.vertical)
        self.image_display = wx.staticbitmap(panel, size=(600, 400))
        right_sizer.add(self.image_display, 1, wx.expand | wx.all, 5)
        
        # 将左右两侧添加到主sizer
        main_sizer.add(left_sizer, 0, wx.expand | wx.all, 5)
        main_sizer.add(right_sizer, 1, wx.expand | wx.all, 5)
        
        # 绑定事件
        select_btn.bind(wx.evt_button, self.on_select)
        rotate_btn.bind(wx.evt_button, self.on_rotate)
        merge_btn.bind(wx.evt_button, self.on_merge)
        compress_btn.bind(wx.evt_button, self.on_compress)
        self.list_box.bind(wx.evt_listbox, self.on_select_image)
        
        panel.setsizer(main_sizer)
        self.setsize((900, 600))
        self.centre()
        
    def update_image_display(self, pil_image):
        """更新图片显示"""
        if pil_image:
            try:
                # 确保图片是rgb模式
                if pil_image.mode != 'rgb':
                    pil_image = pil_image.convert('rgb')
                
                # 获取显示区域的大小
                display_size = self.image_display.getsize()
                image_size = pil_image.size
                
                # 计算缩放比例
                ratio = min(display_size[0]/image_size[0], 
                          display_size[1]/image_size[1])
                new_size = (int(image_size[0] * ratio), 
                          int(image_size[1] * ratio))
                
                # 调整图片大小
                resized_image = pil_image.resize(new_size, image.resampling.lanczos)
                
                # 转换为wx.bitmap
                image_buffer = bytesio()
                resized_image.save(image_buffer, format='png')
                image_buffer.seek(0)  # 重置缓冲区指针到开始位置
                wx_image = wx.image(image_buffer, type=wx.bitmap_type_png)
                wx_bitmap = wx_image.converttobitmap()
                
                # 更新显示
                self.image_display.setbitmap(wx_bitmap)
                self.current_image = wx_bitmap
                self.current_pil_image = pil_image
                
                # 刷新显示
                self.image_display.refresh()
            except exception as e:
                wx.messagebox(f'处理图片时出错: {str(e)}', '错误', wx.ok | wx.icon_error)
            
            # 计算缩放比例
            ratio = min(display_size[0]/image_size[0], 
                       display_size[1]/image_size[1])
            new_size = (int(image_size[0] * ratio), 
                       int(image_size[1] * ratio))
            
            # 调整图片大小
            resized_image = pil_image.resize(new_size, image.resampling.lanczos)
            
            # 转换为wx.bitmap
            image_buffer = bytesio()
            resized_image.save(image_buffer, format='png')
            image_buffer.seek(0)  # 重置缓冲区指针到开始位置
            wx_image = wx.image(image_buffer, type=wx.bitmap_type_png)
            wx_bitmap = wx_image.converttobitmap()
            
            # 更新显示
            self.image_display.setbitmap(wx_bitmap)
            self.current_image = wx_bitmap
            self.current_pil_image = pil_image
            
            # 刷新显示
            self.image_display.refresh()
        
    def on_select(self, event):
        with wx.filedialog(self, "选择图片文件", wildcard="图片文件 (*.jpg;*.png)|*.jpg;*.png",
                         style=wx.fd_open | wx.fd_file_must_exist | wx.fd_multiple) as filedialog:
            
            if filedialog.showmodal() == wx.id_cancel:
                return
                
            paths = filedialog.getpaths()
            self.selected_images.extend(paths)
            self.list_box.set([os.path.basename(path) for path in self.selected_images])
            
    def on_select_image(self, event):
        """当在列表中选择图片时触发"""
        selection = self.list_box.getselection()
        if selection != wx.not_found:
            try:
                image_path = self.selected_images[selection]
                # 使用二进制模式读取图片
                with image.open(image_path) as img:
                    # 创建一个副本以确保图片被完全加载
                    pil_image = img.copy()
                    self.update_image_display(pil_image)
            except exception as e:
                wx.messagebox(f'无法打开图片: {str(e)}', '错误', 
                            wx.ok | wx.icon_error)
                
    def on_rotate(self, event):
        """旋转当前显示的图片"""
        if self.current_pil_image:
            # 顺时针旋转90度
            try:
                rotated_image = self.current_pil_image.rotate(-90, expand=true)
                self.update_image_display(rotated_image)
            except exception as e:
                wx.messagebox(f'旋转图片时出错: {str(e)}', '错误', wx.ok | wx.icon_error)
        else:
            wx.messagebox('请先选择一张图片', '提示', 
                         wx.ok | wx.icon_information)
            
    def on_merge(self, event):
        if len(self.selected_images) < 2:
            wx.messagebox('请至少选择两张图片', '提示', 
                         wx.ok | wx.icon_information)
            return
            
        max_width = 0
        total_height = 0
        
        images = []
        for img_path in self.selected_images:
            img = image.open(img_path)
            max_width = max(max_width, img.width)
            total_height += img.height
            images.append(img)
            
        merged_image = image.new('rgb', (max_width, total_height))
        
        current_height = 0
        for img in images:
            if img.width < max_width:
                x_offset = (max_width - img.width) // 2
            else:
                x_offset = 0
                
            merged_image.paste(img, (x_offset, current_height))
            current_height += img.height
            
        save_path = os.path.join(os.path.dirname(self.selected_images[0]), 
                                'merged.jpg')
        merged_image.save(save_path)
        wx.messagebox(f'图片已合并保存至: {save_path}', '成功', 
                     wx.ok | wx.icon_information)
        
    def on_compress(self, event):
        merged_path = os.path.join(os.path.dirname(self.selected_images[0]), 
                                 'merged.jpg')
        if not os.path.exists(merged_path):
            wx.messagebox('请先合并图片', '提示', wx.ok | wx.icon_information)
            return
            
        img = image.open(merged_path)
        width = int(img.width * 0.5)
        height = int(img.height * 0.5)
        compressed_img = img.resize((width, height), image.resampling.lanczos)
        
        save_path = os.path.join(os.path.dirname(merged_path), 'compressed.jpg')
        compressed_img.save(save_path, quality=85, optimize=true)
        wx.messagebox(f'压缩后的图片已保存至: {save_path}', '成功', 
                     wx.ok | wx.icon_information)

def main():
    app = wx.app()
    frame = imageprocessorframe()
    frame.show()
    app.mainloop()

if __name__ == '__main__':
    main()

功能概述

该工具的主要功能包括:

  • 选择图片:从本地文件中选择图片并显示在列表中。
  • 图片预览:点击列表项可在右侧区域预览图片。
  • 图片旋转:支持顺时针旋转当前显示的图片。
  • 图片合并:将多张图片垂直合并为一张新图片。
  • 图片压缩:对合并后的图片进行尺寸压缩。

代码结构与模块解析

import wx
from pil import image
import os
from io import bytesio

模块说明

wx:提供图形用户界面支持,用于设计窗口、按钮、列表等组件。

pillow (pil):python图像处理库,支持加载、旋转、缩放、保存图片等功能。

os:用于文件路径操作。

io.bytesio:内存中的二进制流,用于将 pil 图片转换为 wx.bitmap 显示。

主类 imageprocessorframe

imageprocessorframe 继承自 wx.frame,是程序的主窗口,负责布局、事件绑定和功能处理。

class imageprocessorframe(wx.frame):
    def __init__(self):
        super().__init__(parent=none, title='图片处理工具')
        self.selected_images = []  # 存储已选择的图片路径
        self.current_image = none  # 当前显示的图片(wx.bitmap)
        self.current_pil_image = none  # 当前显示的 pil 图片对象
        self.init_ui()

界面初始化

init_ui 方法负责创建和布局界面组件,包括按钮、列表框和图片显示区域。

def init_ui(self):
    panel = wx.panel(self)
    main_sizer = wx.boxsizer(wx.horizontal)  # 主布局,水平分布

    # 左侧控制面板
    left_sizer = wx.boxsizer(wx.vertical)
    select_btn = wx.button(panel, label='选择图片')
    rotate_btn = wx.button(panel, label='旋转')
    merge_btn = wx.button(panel, label='合并')
    compress_btn = wx.button(panel, label='压缩')
    self.list_box = wx.listbox(panel, size=(200, 300))

    left_sizer.add(select_btn, 0, wx.all | wx.expand, 5)
    left_sizer.add(self.list_box, 1, wx.all | wx.expand, 5)
    left_sizer.add(rotate_btn, 0, wx.all | wx.expand, 5)
    left_sizer.add(merge_btn, 0, wx.all | wx.expand, 5)
    left_sizer.add(compress_btn, 0, wx.all | wx.expand, 5)

    # 右侧图片显示区域
    right_sizer = wx.boxsizer(wx.vertical)
    self.image_display = wx.staticbitmap(panel, size=(600, 400))
    right_sizer.add(self.image_display, 1, wx.expand | wx.all, 5)

    # 将左右两侧添加到主布局
    main_sizer.add(left_sizer, 0, wx.expand | wx.all, 5)
    main_sizer.add(right_sizer, 1, wx.expand | wx.all, 5)

    # 绑定按钮事件
    select_btn.bind(wx.evt_button, self.on_select)
    rotate_btn.bind(wx.evt_button, self.on_rotate)
    merge_btn.bind(wx.evt_button, self.on_merge)
    compress_btn.bind(wx.evt_button, self.on_compress)
    self.list_box.bind(wx.evt_listbox, self.on_select_image)

    panel.setsizer(main_sizer)
    self.setsize((900, 600))
    self.centre()

布局细节:

  • 左侧为按钮和图片列表框。
  • 右侧为图片显示区域。
  • 使用 wx.boxsizer 管理布局,保证界面响应式。

按钮绑定:

  • on_select:选择图片并添加到列表。
  • on_rotate:旋转当前图片。
  • on_merge:合并图片。
  • on_compress:压缩图片。

核心功能实现

图片选择

def on_select(self, event):
    with wx.filedialog(self, "选择图片文件", wildcard="图片文件 (*.jpg;*.png)|*.jpg;*.png",
                       style=wx.fd_open | wx.fd_file_must_exist | wx.fd_multiple) as filedialog:

        if filedialog.showmodal() == wx.id_cancel:
            return

        paths = filedialog.getpaths()  # 获取选择的文件路径
        self.selected_images.extend(paths)  # 添加到已选择列表
        self.list_box.set([os.path.basename(path) for path in self.selected_images])  # 显示文件名

功能:

打开文件对话框,支持多选。

将选择的图片路径存储到 self.selected_images,并更新列表框显示。

图片显示与预览

def update_image_display(self, pil_image):
    if pil_image:
        try:
            if pil_image.mode != 'rgb':
                pil_image = pil_image.convert('rgb')

            display_size = self.image_display.getsize()
            image_size = pil_image.size
            ratio = min(display_size[0]/image_size[0], display_size[1]/image_size[1])
            new_size = (int(image_size[0] * ratio), int(image_size[1] * ratio))

            resized_image = pil_image.resize(new_size, image.resampling.lanczos)

            image_buffer = bytesio()
            resized_image.save(image_buffer, format='png')
            wx_image = wx.image(image_buffer, type=wx.bitmap_type_png)
            wx_bitmap = wx_image.converttobitmap()

            self.image_display.setbitmap(wx_bitmap)
            self.current_image = wx_bitmap
            self.current_pil_image = pil_image
            self.image_display.refresh()
        except exception as e:
            wx.messagebox(f'处理图片时出错: {str(e)}', '错误', wx.ok | wx.icon_error)

功能:

将 pil 图片调整为适合显示区域的大小。

转换为 wx.bitmap 后显示在 staticbitmap 中。

图片旋转

def on_rotate(self, event):
    if self.current_pil_image:
        try:
            rotated_image = self.current_pil_image.rotate(-90, expand=true)
            self.update_image_display(rotated_image)
        except exception as e:
            wx.messagebox(f'旋转图片时出错: {str(e)}', '错误', wx.ok | wx.icon_error)
    else:
        wx.messagebox('请先选择一张图片', '提示', wx.ok | wx.icon_information)

功能:

使用 pillow.image 的 rotate 方法实现顺时针旋转。

图片合并

def on_merge(self, event):
    if len(self.selected_images) < 2:
        wx.messagebox('请至少选择两张图片', '提示', wx.ok | wx.icon_information)
        return

    max_width = 0
    total_height = 0
    images = []
    for img_path in self.selected_images:
        img = image.open(img_path)
        max_width = max(max_width, img.width)
        total_height += img.height
        images.append(img)

    merged_image = image.new('rgb', (max_width, total_height))
    current_height = 0
    for img in images:
        x_offset = (max_width - img.width) // 2
        merged_image.paste(img, (x_offset, current_height))
        current_height += img.height

    save_path = os.path.join(os.path.dirname(self.selected_images[0]), 'merged.jpg')
    merged_image.save(save_path)
    wx.messagebox(f'图片已合并保存至: {save_path}', '成功', wx.ok | wx.icon_information)

功能:

  • 计算合并后图片的总尺寸。
  • 使用 image.new 创建空白图片。
  • 将每张图片逐一粘贴。

图片压缩

def on_compress(self, event):
    merged_path = os.path.join(os.path.dirname(self.selected_images[0]), 'merged.jpg')
    if not os.path.exists(merged_path):
        wx.messagebox('请先合并图片', '提示', wx.ok | wx.icon_information)
        return

    img = image.open(merged_path)
    width = int(img.width * 0.5)
    height = int(img.height * 0.5)
    compressed_img = img.resize((width, height), image.resampling.lanczos)

    save_path = os.path.join(os.path.dirname(merged_path), 'compressed.jpg')
    compressed_img.save(save_path, quality=85, optimize=true)
    wx.messagebox(f'压缩后的图片已保存至: {save_path}', '成功', wx.ok | wx.icon_information)

功能:

将合并后的图片尺寸缩小为原来的 50%。

设置压缩质量为 85%,并保存优化后的图片。

运行结果

到此这篇关于使用python实现图片处理工具的文章就介绍到这了,更多相关python图片处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com