前言
通过这段代码可以修改图片的像素尺寸大小
运行截图如下
代码如下:
import tkinter as tk
from tkinter import filedialog, messagebox, colorchooser
from PIL import Image, ImageDraw
class ImageProcessorApp:
def __init__(self, root):
self.root = root
self.root.title("图片处理程序")
# 添加选择文件按钮
self.select_file_button = tk.Button(self.root, text="选择图片文件", command=self.select_file)
self.select_file_button.pack(pady=10)
# 添加尺寸选择按钮
self.select_size_button = tk.Button(self.root, text="选择尺寸", command=self.select_size)
self.select_size_button.pack(pady=10)
# 添加处理图片按钮
self.process_button = tk.Button(self.root, text="处理图片", command=self.process_image)
self.process_button.pack(pady=20)
# 初始化变量
self.input_path = None
self.output_path = None
self.new_size = None
def select_file(self):
self.input_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg;*.png;*.jpeg")])
if self.input_path:
messagebox.showinfo("文件选择", f"选择的文件:{self.input_path}")
def select_size(self):
size_dialog = tk.Toplevel(self.root)
size_dialog.title("选择尺寸")
label = tk.Label(size_dialog, text="输入新尺寸(宽 x 高):")
label.pack(padx=10, pady=10)
self.width_entry = tk.Entry(size_dialog)
self.width_entry.pack(padx=10, pady=5)
self.height_entry = tk.Entry(size_dialog)
self.height_entry.pack(padx=10, pady=5)
confirm_button = tk.Button(size_dialog, text="确认", command=self.set_size)
confirm_button.pack(pady=10)
def set_size(self):
try:
width = int(self.width_entry.get())
height = int(self.height_entry.get())
self.new_size = (width, height)
messagebox.showinfo("尺寸选择", f"选择的尺寸:{self.new_size}")
except ValueError:
messagebox.showerror("错误", "请输入有效的整数尺寸!")
def process_image(self):
if not self.input_path:
messagebox.showerror("错误", "请先选择图片文件!")
return
if not self.new_size:
messagebox.showerror("错误", "请先选择新尺寸!")
return
output_path = filedialog.asksaveasfilename(defaultextension=".jpg",
filetypes=[("JPEG", "*.jpg"), ("PNG", "*.png")])
if output_path:
try:
original_image = Image.open(self.input_path)
new_image = original_image.resize(self.new_size)
if new_image.mode != 'RGB':
new_image = new_image.convert('RGB')
final_image = Image.new("RGB", self.new_size, self.background_color)
final_image.paste(new_image, (0, 0))
final_image.save(output_path)
messagebox.showinfo("完成", f"处理后的图片已保存为:{output_path}")
except Exception as e:
messagebox.showerror("错误", f"处理图片时出错:{e}")
if __name__ == "__main__":
root = tk.Tk()
app = ImageProcessorApp(root)
root.mainloop()