用python做一个压缩图片的小程序
学生正在学习图像的编码与压缩,记录一下这个python小程序,给他们提供一下帮助。需要用到PIL库,记得安装:
pip install pillow
import tkinter as tk
from tkinter import filedialog
from PIL import Image
import tkinter.messagebox as messagebox
class ImageCompressor:
def __init__(self, window):
self.window = window
self.window.title("图片压缩工具By ZYX 2023")
self.source_path = tk.StringVar()
self.output_path = tk.StringVar()
frame1 = tk.Frame(window)
frame1.pack(padx=5, pady=5)
lbl_source = tk.Label(frame1, text="原始图片路径:")
lbl_source.pack(side=tk.LEFT)
entry_source = tk.Entry(frame1,textvariable=self.source_path, width=40)
entry_source.pack(side=tk.LEFT)
btn_source =tk.Button(frame1, text="打开", command=self.open_source_image)
btn_source.pack(side=tk.LEFT)
frame2 = tk.Frame(window)
frame2.pack(padx=5, pady=5)
lbl_output = tk.Label(frame2, text="输出图片路径:")
lbl_output.pack(side=tk.LEFT)
entry_output = tk.Entry(frame2,textvariable=self.output_path, width=40)
entry_output.pack(side=tk.LEFT)
btn_output =tk.Button(frame2, text="保存", command=self.save_output_image)
btn_output.pack(side=tk.LEFT)
quality_label = tk.Label(window, text='质量(1-95):')
quality_label.pack(pady=5)
self.quality_slider = tk.Scale(window, from_=1, to=95,
length=400,tickinterval=19,
orient='horizontal', resolution=1)
self.quality_slider.set(80)
self.quality_slider.pack()
btn_compress =tk.Button(window, text="开始压缩", command=self.compress_image)
btn_compress.pack(pady=10)
def open_source_image(self):
file_path = filedialog.askopenfilename()
self.source_path.set(file_path)
def save_output_image(self):
file_path = filedialog.asksaveasfilename(defaultextension=".jpg")
self.output_path.set(file_path)
def compress_image(self):
try:
img = Image.open(self.source_path.get())
img.save(self.output_path.get(), "JPEG", quality=self.quality_slider.get())
messagebox.showinfo("成功", "图片压缩成功!")
except Exception as e:
messagebox.showerror("失败", f"压缩过程中发生错误:{e}")
if __name__ == '__main__':
window = tk.Tk()
app = ImageCompressor(window)
window.mainloop()