import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
def select_image():
global img, img_path
img_path = filedialog.askopenfilename(
filetypes=[("Image Files", "*.jpg;*.jpeg;*.png;*.bmp;*.gif")]
)
if not img_path:
return
img = Image.open(img_path)
preview_image(img)
def preview_image(image):
# Resize for preview
preview = image.copy()
preview.thumbnail((300, 300))
tk_img = ImageTk.PhotoImage(preview)
img_label.config(image=tk_img)
img_label.image = tk_img
def resize_image():
global img, img_path
if not img_path:
messagebox.showerror("Error", "No image selected!")
return
try:
new_width = int(width_entry.get())
new_height = int(height_entry.get())
resized_img = img.resize((new_width, new_height))
save_path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG files", "*.png"), ("JPEG files", "*.jpg"), ("All files", "*.*")]
)
if save_path:
resized_img.save(save_path)
messagebox.showinfo("Success", f"Image saved to {save_path}")
except ValueError:
messagebox.showerror("Error", "Please enter valid width and height values!")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
# GUI Setup
root = tk.Tk()
root.title("Image Resizer")
frame = tk.Frame(root)
frame.pack(pady=10)
# Image Preview
img_label = tk.Label(frame)
img_label.pack()
# Select Image Button
select_btn = tk.Button(root, text="Select Image", command=select_image)
select_btn.pack(pady=5)
# Input Fields for Width and Height
size_frame = tk.Frame(root)
size_frame.pack(pady=5)
tk.Label(size_frame, text="Width: ").grid(row=0, column=0, padx=5)
width_entry = tk.Entry(size_frame, width=10)
width_entry.grid(row=0, column=1, padx=5)
tk.Label(size_frame, text="Height: ").grid(row=0, column=2, padx=5)
height_entry = tk.Entry(size_frame, width=10)
height_entry.grid(row=0, column=3, padx=5)
# Resize Button
resize_btn = tk.Button(root, text="Resize and Save", command=resize_image)
resize_btn.pack(pady=10)
root.mainloop()
No comments:
Post a Comment