基于Python开发PPTX压缩工具

2025-02-09 04:50

本文主要是介绍基于Python开发PPTX压缩工具,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《基于Python开发PPTX压缩工具》在日常办公中,PPT文件往往因为图片过大而导致文件体积过大,不便于传输和存储,所以本文将使用Python开发一个PPTX压缩工具,需要的可以了解下...

引言

在日常办公中,PPT文件往往因为图片过大而导致文件体积过大,不便于传输和存储。为了应对这一问题,我们可以使用pythonwxPython图形界面库结合python-pptxPillow,开发一个简单的PPTX压缩工具。本文将详细介绍如何实现这一功能。

全部代码

import wx
import os
from pptx import Presentation
from PIL import Image
import io

class CompressorFrame(wx.Frame):
    def __init__(self):
        super().__init__(parent=None, title="基于Python开发PPTX压缩工具")
        self.panel = wx.Panel(self)
        self.create_ui()
        
    def create_ui(self):
        vbox = wx.BoxSizer(wx.VERTICAL)
        
        # 文件选择部分
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.file_path = wx.TextCtrl(self.panel, size=(300, -1))
        browse_btn = wx.Button(self.panel, label='选择文件')
        browse_btn.Bind(wx.EVT_BUTTON, self.on_browse)
        hbox1.Add(self.file_path, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        hbox1.Add(browse_btn, flag=wx.ALL, border=5)
        
        # 压缩按钮
        compress_btn = wx.Button(self.panel, label='开始压缩')
        compress_btn.Bind(wx.EVT_BUTTON, self.on_compress)
        
        # 进度条
        self.progress = wx.Gauge(self.panel, range=100, size=(400, 25))
        
        # 状态文本
        self.status_text = wx.StaticText(self.panel, label="")
        
        vbox.Add(hbox1, flag=wx.EXPAND|wx.ALL, border=5)
        vbox.Add(compress_btn, flag=wx.ALIGN_CENTER|wx.ALL, border=5)
        vbox.Add(self.progress, flag=wx.EXPAND|wx.ALL, border=5)
        vbox.Add(self.status_text, flag=wx.EXPAND|wx.ALL, border=5)
        
        self.panel.SetSizer(vbox)
        self.Fit()
        
    def on_browse(self, event):
        with wx.FileDialog(self, "选择PPTX文件", wildcard="PowerPoint files (*.pptx)|*.pptx",
                         style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return
            path = fileDialog.GetPath()
            path = os.path.normpath(path.strip('"'))
            self.file_path.SetValue(path)
            
    def update_status(self, text):
        wx.CallAfter(self.status_text.SetLabel, text)
            
    def on_compress(self, event):
        if not self.file_path.GetValue():
            wx.MessageBox('请先选择文件', '提示', wx.OK | wx.ICON_INFORMATION)
            return
            
        input_path = self.file_path.GetValue().strip('"')
        input_path = os.path.normpath(input_path)
        
        if not os.path.exists(input_path):
            wx.MessageBox('文件不存在,请检查路径', '错误', wx.OK | wx.ICON_ERROR)
            return
            
        output_path = self._get_output_path(input_path)
        
        try:
            self._compress_pptx(input_path, output_path)
            wx.MessageBox('压缩完成www.chinasem.cn!\n保存路径:' + output_path, 
                         '成功', wx.OK | wx.ICON_INFORMATION)
        except Exception as e:
            wx.MessageBox(f'压缩过程中出错:{str(e)}', 
                         '错误', wx.OK | wx.ICON_ERROR)
        finally:
            self.progress.SetValue(0)
            self.update_status("")
            
    def _get_output_path(self, input_path):
        directory = os.path.dirname(input_path)
        filename = os.path.basename(input_path)
        name, ext = os.path.splitext(filename)
        return os.path.join(directory, f"{name}_compressed{ext}")
        
    def _compress_pptx(self, input_path, output_path):
        try:
            prs = Presentation(input_path)
        except Exception as e:
            raise Exception(f"无法打开PPTX文件: {str(e)}")
            
        total_slides = len(prs.slides)
        processed_images = 0
        skipped_images = 0
        
        for i, slide in enumerate(prs.slides):
            self.update_status(f"正在处理第 {i+1}/{total_slides} 张幻灯片")
            
            shapes_with_images = []
            for shape in slide.shapes:
                if hasattr(shape, "image"):
                    shapes_with_images.append(shape)
            
            for shape in shapes_with_images:
                try:
                    # 获取图片数据
                    image_bytes = shape.image.blob
                    
                    # 使用PIL压缩图片
                    with Image.open(io.BytesIO(image_bytes)) as img:
                        # 转换RGBA为RGB
                        if img.mode == 'RGBA':
                            img = img.convert('RGB')
                            
                        # 压缩图片
                        # 如果图片较大,调整尺寸
                        max_size = 800  # 最大尺寸为1024像素
                        if img.width > max_size or img.height > max_size:
                            ratio = min(max_size/img.width, max_size/img.height)
                            new_size = (int(img.width * ratio), int(img.height * ratio))
                            img = img.resize(new_size, Image.LANCZOS)
                        
                        output_buffer = io.BytesIO()
                        img.save(output_buffer, format='JPEG', quality=10, optimize=True)
                        
                        # 替换原图片
                        shape._element.blip.embed.rId = shape._element.blip.embed.rId
                        new_image = output_buffer.getvalue()
                        
                        # 更新图片数据
                        image_part = shape.image
                        image_part._blob = new_image
                        
                    processed_images += 1
                except Exception as e:
                    print(f"处理图片时出错: {str(e)}")
                    skipped_http://www.chinasem.cnimages += 1
                    continue
                    
            # 更新进度条
            progress = int((i + 1) / total_slides * 100)
            wx.CallAfter(self.progress.SetValue, progress)
            
        self.update_status(f"完成!成功处理 {processed_images} 张图片,跳过 {skipped_images} 张图片")
            
        try:
            prs.save(output_path)
        except Exception as e:
            raise Exception(f"保存文件时出错: {str(e)}")

def main():
    app = wx.App()
    frame = CompressorFrame()
    frame.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

环境准备

在开始之前,我们需要安装以下Python库:

  • wxPython:用于创建图形用户界面
  • python-pptx:用于处理PPTX文件
  • Pillow:用于图片压缩

安装命令:

pip install wxPython python-pptx Pillow

代码结构

代码主要包括以下几个部分:

  • 图形界面设计
  • 文件选择与压缩功能
  • 图片压缩逻辑

代码实现

导入必要模块

import wx
import os
from pptx import Presentation
from PIL import Image
import io

创建主窗口

主窗口CompressorFrame继承自wx.Frame,用于展示UI组件。

class CompressorFrame(wx.Frame):
    def __init__(self):
        super().__init_php_(parent=None, title="基于Python开发PPTX压缩工具")
        self.panel = wx.Panel(self)
        self.create_ui()
        
    def create_ui(self):
        vbox = wx.BoxSizer(wx.VERTICAL)
        
        # 文件选择部分
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.file_path = wx.TextCtrl(self.panel, size=(300, -1))
        browse_btn = wx.Button(self.panel, label='选择文件')
        browse_btn.Bind(wx.EVT_BUTTON, self.on_browse)
        hbox1.Add(self.file_path, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        hbox1.Add(browse_btn, flag=wx.ALL, border=5)
        
        # 压缩按钮
        compress_btn = wx.Button(self.panel, label='开始压缩')
        compress_btn.Bind(wx.EVT_BUTTON, self.on_compress)
        
        # 进度条
        self.progress = wx.Gauge(self.panel, range=100, size=(400, 25))
        
        # 状态文本
        self.status_text = wx.StaticText(self.panel, label="")
        
        vbox.Add(hbox1, flag=wx.EXPAND|wx.ALL, border=5)
        vbox.Add(compress_btn, flag=wx.ALIGN_CENTER|wx.ALL, border=5)
        vbox.Add(self.progress, flag=wx.EXPAND|wx.ALL, border=5)php
        vbox.Add(self.status_text, flag=wx.EXPAND|wx.ALL, border=5)
        
        self.panel.SetSizer(vbox)
        self.Fit()

文件选择功能

通过文件对话框让用户选择PPTX文件。

def on_browse(self, event):
    with wx.FileDialog(self, "选择PPTX文件", wildcard="PowerPoint files (*.pptx)|*.pptx",
                     style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
        if fileDialog.ShowModal() == wx.ID_CANCEL:
            return
        path = fileDialog.GetPath()
        self.file_path.SetValue(os.path.normpath(path.strip('"')))

压缩功能实现

压缩图片逻辑:

  • 使用Pillow库压缩PPT中的图片,将其转换为JPEG格式,并降低质量以减少文件大小。
  • 限制图片的最大尺寸,保持图片的可视质量。

更新进度条与状态:

使用wx.Gauge展示处理进度。

实时更新处理状态。

def _compress_pptx(self, input_path, output_path):
    prs = Presentation(input_path)
    total_slides = len(prs.slides)
    processed_images = 0
    skipped_images = 0
    
    for i, slide in enumerate(prs.slides):
        self.update_status(f"正在处理第 {i+1}/{total_slides} 张幻灯片")
        
        shapes_with_images = [shape for shape in slide.shapes if hasattr(shape, "image")]
        
        for shape in shapes_with_images:
            try:
                image_bytes = shape.image.blob
                with Image.open(io.BytesIO(image_bytes)) as img:
                    if img.mode == 'RGBA':
                        img = img.convert('RGB')
                    max_size = 800
                    if img.width > max_size or img.height > max_size:
                        ratio = min(max_size/img.width, max_size/img.height)
                        new_size = (int(img.width * ratio), int(img.height * ratio))
                        img = img.resize(new_size, Image.LANCZOS)
                    output_buffer = io.BytesIO()
                    img.save(output_bphpuffer, format='JPEG', quality=10, optimize=True)
                    new_image = output_buffer.getvalue()
                    shape.image._blob = new_image
                processed_images += 1
            except Exception as e:
                print(f"处理图片时出错: {str(e)}")
                skipped_images += 1
        wx.CallAfter(self.progress.SetValue, int((i + 1) / total_slides * 100))
    
    self.update_status(f"完成!成功处理 {processed_images} 张图片,跳过 {skipped_images} 张图片")
    prs.save(output_path)

主函数

启动wxPython应用程序。

def main():
    app = wx.App()
    frame = CompressorFrame()
    frame.Show()
    app.MainLoop()

​​​​​​​if __name__ == '__main__':
    main()

运行结果

基于Python开发PPTX压缩工具

到此这篇关于基于Python开发PPTX压缩工具的文章就介绍到这了,更多相关Python PPTX压缩内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于基于Python开发PPTX压缩工具的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153356

相关文章

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文