图片体积压缩工具源码
作者:小编日期:2026-01-19浏览:5016分类:只有源码
因为工作需要,需要压缩图片的大小,基本都是小于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()
相关文章
- 06-05 多语言自定义产品系统/企鹅养殖投资返利/一键安装
- 06-05 戒了么 v4.2 最新版 签到打卡源码
- 06-05 全新祈福导航系统源码V1.1 毛玻璃UI效果 支持ping延迟
- 05-25 一个非常漂亮炫丽 AI大模型聚合导航源码
- 05-25 WordPress 子比主题-账号切换插件
- 05-24 Z-Blog 经典主题 雷霆资源网主题源码 全开源·无后门
- 05-20 全新UI 阅后即焚V2正式版系统源码 全开源
- 05-19 网页版文件(证照、档案、合同等)管理系统
- 05-12 卡密领取系统源码 每天限制领取次数
- 05-12 全新UI随机美女短视频管理系统源码 带后台运营版
- 05-05 最新去水印小程序系统 前端+后端全套源码 多套模版 免授权
- 05-05 游嘻CMSv1.1.0最新版本-全网游戏一键采集伪原创
取消回复欢迎你发表评论:
- 协助本站优化一下
- 最近发表
- 1唯品会618每天抽6.18亓红包
- 2汽车之家周年庆领免费洗车券
- 3变声器V1.02 解锁VIP功能
- 4【咸鱼视频】4.0.4 高清影视综艺资源免费无广告
- 5【快追影视】1.1.2 高清热门影视免费无广告
- 6【mio动漫】1.0.0 热门番剧免费看 实时更新 VIP
- 7Sweet Selfie 照片美化编辑 v5.7.1769 解锁专业版
- 8Kilonotes 千本笔记 v3.28.1 解锁VIP会员版
- 9爱电影 v6.6.9 去广告纯净版
- 10快影 v7.42.0.742005 去广告去水印版
- 11PhotoArt 人工智能照片编辑器 v1.9.05 解锁高级订阅版
- 12AirBrush Ai智能修图 v8.9.0 解锁高级版
- 13【三号动漫】1.4.0 热门高清番剧实时更新 无广告
- 14【爱看影视】5.3.6 影视剧集免费高清无广告
- 15qBittorrent BT下载工具 v5.2.1.10 中文绿色便携增强版
Copyright© XGW9.COM版权所有〖小庚资源网〗
〖恒创科技〗为本站提供专业云计算服务
本站发布的内容来源于互联网,如果有侵权内容,请联系我们删除!E-mail:xgzyw6@outlook.com
关于我们|我要投稿|免责声明|XML地图













暂无评论,来添加一个吧。