图片体积压缩工具源码

258次阅读
没有评论

共计 3100 个字符,预计需要花费 8 分钟才能阅读完成。

因为工作需要,需要压缩图片的大小,基本都是小于 100K 的,就压缩体积,用不着其他的功能,于是就有了这个代码,也可以自定义压缩多大,但是不那么精确,还导入多张图片
图片体积压缩工具源码 图片体积压缩工具源码

import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image
import os
 
class ImageCompressor:
    def __init__(self, root):
        self.root = root
        self.root.title("图片压缩工具 - 目标大小: 100KB 以内")
        self.root.geometry("500x400")
         
        self.target_size = tk.IntVar(value=100)
        self.create_widgets()
 
    def create_widgets(self):
        target_frame = tk.Frame(self.root)
        target_frame.pack(pady=5)
         
        tk.Label(target_frame, text="目标大小 (KB):").pack(side=tk.LEFT)
        self.target_size_entry = tk.Entry(target_frame, width=10, textvariable=self.target_size)
        self.target_size_entry.pack(side=tk.LEFT, padx=5)
         
        tk.Button(target_frame, text="设置", command=self.set_target_size).pack(side=tk.LEFT)
         
        self.select_btn = tk.Button(self.root, text="选择图片", command=self.select_images)
        self.select_btn.pack(pady=10)
        self.file_label = tk.Label(self.root, text="未选择图片", wraplength=400)
        self.file_label.pack(pady=5)
 
        self.compress_btn = tk.Button(self.root, text="开始压缩", command=self.compress_images, state=tk.DISABLED)
        self.compress_btn.pack(pady=10)
 
        self.progress_label = tk.Label(self.root, text="")
        self.progress_label.pack(pady=5)
 
        self.result_text = tk.Text(self.root, height=10, width=60)
        self.result_text.pack(pady=10)
 
        self.clear_btn = tk.Button(self.root, text="清空结果", command=self.clear_results)
        self.clear_btn.pack(pady=5)
 
        self.image_paths = []
     
    def set_target_size(self):
        """设置目标压缩大小"""
        try:
            size = int(self.target_size.get())
            if size <= 0:
                messagebox.showerror("错误", "目标大小必须大于 0KB")
                return
            if size > 10000:  
                messagebox.showwarning("警告", "目标大小过大,建议设置一个小于 10MB 的值")
             
            self.root.title(f"图片压缩工具 - 目标大小: {size}KB 以内")
            messagebox.showinfo("成功", f"目标大小已设置为: {size}KB")
        except ValueError:
            messagebox.showerror("错误", "请输入有效的数字")
 
    def select_images(self):
        file_paths = filedialog.askopenfilenames(
            title="选择要压缩的图片",
            filetypes=[("Image files", "*.jpg *.jpeg *.png *.bmp *.tiff *.webp"),
                ("All files", "*.*")
            ]
        )
         
        if file_paths:
            self.image_paths = list(file_paths)
            self.file_label.config(text=f"已选择 {len(self.image_paths)} 张图片")
            self.compress_btn.config(state=tk.NORMAL)
            self.result_text.insert(tk.END, f"已选择 {len(self.image_paths)} 张图片 \n")
            for path in self.image_paths:
                self.result_text.insert(tk.END, f"- {path}\n")
 
    def compress_images(self):
        if not self.image_paths:
            messagebox.showerror("错误", "请选择至少一张图片")
            return
 
        total_images = len(self.image_paths)
        success_count = 0
         
        for i, image_path in enumerate(self.image_paths):
            try:
                self.progress_label.config(text=f"正在处理第 {i+1}/{total_images} 张图片...")
                self.root.update()
                 
                original_size = os.path.getsize(image_path) / 1024 
                self.result_text.insert(tk.END, f"\n 处理图片: {os.path.basename(image_path)}\n")
                self.result_text.insert(tk.END, f"原始大小: {original_size:.2f} KB\n")
 
                img = Image.open(image_path)
 
                if img.mode in ('RGBA', 'LA', 'P'):
                    img = img.convert('RGB')
 
                output_path = self.generate_output_path_batch(image_path)
 
                quality = 95
 
                while True:
                    img.save(output_path, "JPEG", optimize=True, quality=quality)
 
                    compressed_size = os.path.getsize(output_path) / 1024 
                     
                    self.progress_label.config(text=f"正在处理: {os.path.basename(image_path)}, 当前质量: {quality}, 大小: {compressed_size:.2f}KB")
                    self.root.update()
 
                    if compressed_size <= self.target_size.get() or quality <= 10:
                        break
 
                    if compressed_size > self.target_size.get() * 1.5: 
                        quality -= 15
                    elif compressed_size > self.target_size.get() * 1.2:
                        quality -= 8
                    else:
                        quality -= 5
                     
                    quality = max(quality, 10)
 
                final_size = os.path.getsize(output_path) / 1024
                self.result_text.insert(tk.END, f"最终质量: {quality}, 最终大小: {final_size:.2f} KB\n")
                 
                if final_size <= self.target_size.get():
                    self.result_text.insert(tk.END, f"✅ 压缩成功! 文件已保存至: {output_path}\n")
                    success_count += 1
                else:
                    self.result_text.insert(tk.END, f"⚠️ 无法压缩到 {self.target_size.get()}KB 以下,最低压缩到: {final_size:.2f} KB\n")
                 
                self.root.update()
                 
            except Exception as e:
                self.result_text.insert(tk.END, f"❌ 压缩失败: {str(e)}\n")
                messagebox.showerror("错误", f"压缩过程中出现错误: {str(e)}")
         
        self.progress_label.config(text="完成!")
        messagebox.showinfo("完成", f"批量压缩完成!\n 总共处理: {total_images} 张图片 \n 成功压缩: {success_count} 张图片 \n 无法压缩到 {self.target_size.get()}KB 以下: {total_images - success_count} 张图片")
 
    def generate_output_path_batch(self, input_path):
        """为批量处理生成输出文件路径"""
        base_name, ext = os.path.splitext(input_path)
        counter = 1
        while True:
            output_path = f"{base_name}_compressed_{counter}.jpg"
            if not os.path.exists(output_path):
                return output_path
            counter += 1
 
    def generate_output_path(self):
        """生成输出文件路径"""
        base_name, ext = os.path.splitext(self.image_path)
        counter = 1
        while True:
            output_path = f"{base_name}_compressed_{counter}.jpg"
            if not os.path.exists(output_path):
                return output_path
            counter += 1
 
    def clear_results(self):
        self.result_text.delete(1.0, tk.END)
 
    def compress_image(self):
        pass
 
if __name__ == "__main__":
    root = tk.Tk()
    app = ImageCompressor(root)
    root.mainloop()

正文完
 0
suyan
版权声明:本站原创文章,由 suyan 于2026-01-19发表,共计3100字。
转载说明:转载本网站任何内容,请按照转载方式正确书写本站原文地址。本站提供的一切软件、教程和内容信息仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑或手机中彻底删除上述内容。如果您喜欢该程序,请支持正版,购买注册,得到更好的正版服务。如有侵权请邮件QQ邮箱:suyanw520@163.com 与我们联系处理。敬请谅解!
评论(没有评论)
验证码