图片体积压缩工具源码
作者:小编日期:2026-01-19浏览:4924分类:只有源码
因为工作需要,需要压缩图片的大小,基本都是小于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()
相关文章
- 02-20 小奈猫狗情侣博客v1.0.0
- 02-15 软件库APP开源Flutter SoftLib源码+后端源码
- 02-12 网站维护停运通知源码
- 02-12 精美导航引导页HTML源码,自适应手机/电脑
- 02-10 2026最新多模板导航网源码
- 02-08 2026最新我爱导航V2.0.5系统源码,全新修复+美化版(自动来路IP排第一)
- 02-08 域DNS多级域名分发系统(程序)V1.0免费使用
- 02-05 梦幻企业投诉1.0版本系统,模仿微信投诉
- 02-05 迅风DNS Pro二级域名分发全新V3.1.2系统源码
- 02-03 六零导航页2.1版本最新修复完美版本
- 02-03 全新UI购物商城系统源码发布 | PHP + 易支付 | 账号密码注册
- 01-31 表情密文翻译器源码HTML源码
取消回复欢迎你发表评论:
- 协助本站优化一下
- 最近发表
- 1【一个工具箱】1.0.6 万能工具大全 解锁VIP功能
- 2限时开放微信福利群聊 定时发放实物等福利
- 3【一起刷追剧】1.5.2 热门剧集实时更新 可投屏
- 4灵动锁屏V2.1.1 解锁VIP功能
- 5大海视频V4.3.0 老牌免费追剧神器
- 6【眼福】网红小希裸拍鸳鸯戏舞蹈小庚网专属福利
- 7小奈猫狗情侣博客v1.0.0
- 8 【眼福】网红可可裸拍舞蹈小庚网专属福利 前10送实物福利
- 9【灵虎影视】2.1.0 热门剧集免费看 实时更新 无广告
- 10【去水印神器】3.3.8 万能去水印 解锁VIP功能
- 11水印制造工具V5.3.0 解锁高级功能 免费制作多种形态水印
- 12动漫国V1.0.0.8 最新免费无广告版
- 13【双子星动漫】6.3.3 免费追番神器 无广告
- 14【表白祝福视频制作】1.5 装X必备 解锁VIP
- 15Biu表情包V1.0.0 斗图必备 解锁VIP功能
Copyright© XGW9.COM版权所有〖小庚资源网〗
〖恒创科技〗为本站提供专业云计算服务
本站发布的内容来源于互联网,如果有侵权内容,请联系我们删除!E-mail:xgzyw6@outlook.com
关于我们|我要投稿|免责声明|XML地图










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