今天在某网站发布信息的时候遇到上传图片被限制1MB以内的,可是手机拍照的图片都是4MB左右,上传被拒,突然想起之前学校里面上传资料也是这样的限制,这时候才发现,图片压缩居然很多人还在收费,于是就萌生了自己写一个的念头,废话不多说,我们看结果吧
直接选择需要压缩的图片,然后设置需要压缩的比列,点击开始压缩就可以马上得到需要的图片了!压缩前后图片对比
下面上源代码,写的比较简单,但是绝对好用!
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image
#作者微信:skd8999
def compress_image(input_file, output_file, quality):
image = Image.open(input_file)
# 根据输入文件的扩展名决定保存格式
if input_file.lower().endswith('.png'):
image.save(output_file, "PNG", optimize=True)
else:
image.save(output_file, "JPEG", quality=quality)
def select_image():
file_path = filedialog.askopenfilename(title="选择图片", filetypes=[("Image Files", "*.jpg;*.jpeg;*.png")])
if file_path:
entry_input.delete(0, tk.END)
entry_input.insert(0, file_path)
def start_compression():
input_file = entry_input.get()
quality = entry_quality.get()
try:
quality = int(quality)
if quality < 0 or quality > 100:
raise ValueError("压缩百分比必须在 0 到 100 之间。")
# 生成输出文件名
output_file = f"{input_file.rsplit('.', 1)[0]}_skd8999"
if input_file.lower().endswith('.png'):
output_file += ".png"
else:
output_file += ".jpg"
compress_image(input_file, output_file, quality)
messagebox.showinfo("成功", f"图片已压缩并保存为: {output_file}")
except Exception as e:
messagebox.showerror("错误", str(e))
# 创建主窗口
root = tk.Tk()
root.title("图片压缩工具")
# 输入框和按钮
label_input = tk.Label(root, text="选择图片:")
label_input.pack(pady=5)
entry_input = tk.Entry(root, width=50)
entry_input.pack(pady=5)
button_browse = tk.Button(root, text="浏览", command=select_image)
button_browse.pack(pady=5)
label_quality = tk.Label(root, text="压缩百分比 (0-100):")
label_quality.pack(pady=5)
entry_quality = tk.Entry(root)
entry_quality.pack(pady=5)
button_compress = tk.Button(root, text="开始压缩", command=start_compression)
button_compress.pack(pady=20)
# 运行主循环
root.mainloop()y
也有我做好了的exe软件,免费提供给大家下载使用!也可以联系我索取,下载地址:http://uns028.top:8999/d/UNS/%E5%9B%BE%E7%89%87%E5%8E%8B%E7%BC%A9%E5%B7%A5%E5%85%B7.exe?sign=EYLlG909y0RJQuHbZ7qncpvh9CI1Fif6n1Y9ZXVJFzA=:0