基于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.cppcns.com/jiaoben/python/699701.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1153356

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以