Create an Image Resizer in tkinter

Introduction

This python program creates an tkinter application that allows users to resize images. Users can select an image file, specify new dimensions, choose a file format (JPG or PNG), and rename the resized image. The program utilizes the Pillow library to handle image processing, ensuring that users can easily resize images without needing advanced technical knowledge.

Program

Here is the full program to create an image resizer in tkinter
import os
from tkinter import *
from tkinter import filedialog, messagebox
from PIL import Image

def resize_image(image, resized, size):
    if not os.path.exists(image):
        messagebox.showerror("Error", f"The input image '{image}' does not exist.")
        return

    try:
        with Image.open(image) as img:
            resized_img = img.resize(size)
            resized_img.save(resized)
            messagebox.showinfo("Success", f"Resized image saved to '{resized}' with size {size}")
    except Exception as e:
        messagebox.showerror("Error", f"Error occurred: {e}")

def browse_image():
    file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg;*.png")])
    if file_path:
        image_entry.delete(0, END)
        image_entry.insert(0, file_path)

def resize():
    image_name = image_entry.get()
    rename = rename_entry.get()
    width = width_entry.get()
    height = height_entry.get()

    if not image_name or not rename or not width or not height:
        messagebox.showerror("Error", "Please fill in all fields.")
        return

    try:
        new_size = (int(width), int(height))
        if ext_var.get() == 1:
            resize_name = rename + ".jpg"
        elif ext_var.get() == 2:
            resize_name = rename + ".png"
        else:
            raise ValueError("Invalid file extension choice.")

        resize_image(image_name, resize_name, new_size)

    except ValueError as e:
        messagebox.showerror("Error", f"Error: {e}. Please enter a valid number .")

resizer = Tk()
resizer.title("Image Resizer")

Label(resizer, text="Select Image:").grid(row=0, column=0, padx=10, pady=10)
image_entry = Entry(resizer, width=30)
image_entry.grid(row=0, column=1, padx=10, pady=10)
Button(resizer, text="Browse", command=browse_image).grid(row=0, column=2, padx=10, pady=10)

Label(resizer, text="Rename Resized Image:").grid(row=1, column=0, padx=10, pady=10)
rename_entry = Entry(resizer, width=30)
rename_entry.grid(row=1, column=1, padx=10, pady=10)

Label(resizer, text="Choose Extension:").grid(row=2, column=0, padx=10, pady=10)
ext_var = IntVar()
Radiobutton(resizer, text="JPG", variable=ext_var, value=1).grid(row=2, column=1, sticky=W)
Radiobutton(resizer, text="PNG", variable=ext_var, value=2).grid(row=2, column=2, sticky=W)

Label(resizer, text="Width:").grid(row=3, column=0, padx=10, pady=10)
width_entry = Entry(resizer, width=10)
width_entry.grid(row=3, column=1, padx=10, pady=10)

Label(resizer, text="Height:").grid(row=4, column=0, padx=10, pady=10)
height_entry = Entry(resizer, width=10)
height_entry.grid(row=4, column=1, padx=10, pady=10)

Button(resizer, text="Resize Image", command=resize).grid(row=5, column=1, padx=10, pady=10)
resizer.mainloop()

Program Explanation

We will breakdown the program into simpler parts to understand it easily.

Importing libraries

import os
from tkinter import *
from tkinter import filedialog, messagebox
from PIL import Image

os library is used for interacting with the operating system, particularly for file management.
tkinter library provides tools for creating graphical user interfaces (GUIs).
PIL is a powerful library for opening, manipulating, and saving image files

Image Resizing Function

def resize_image(image, resized, size):
    if not os.path.exists(image):
        messagebox.showerror("Error", f"The input image '{image}' does not exist.")
        return

    try:
        with Image.open(image) as img:
            resized_img = img.resize(size)
            resized_img.save(resized)
            messagebox.showinfo("Success", f"Resized image saved to '{resized}' with size {size}")
    except Exception as e:
        messagebox.showerror("Error", f"Error occurred: {e}")

This function takes an input image path, a resized output path, and the new dimensions. It first checks if the input image exists. If not, it displays an error message. If the image exists, it opens the image, resizes it to the specified dimensions, and saves the resized image. Upon success, it shows a confirmation message. If an error occurs during processing, it displays an error message.

File browsing function

def browse_image():
    file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg;*.png")])
    if file_path:
        image_entry.delete(0, END)
        image_entry.insert(0, file_path)

This function allows users to select an image file through a file dialog. If a file is selected, it clears the previous input in the entry field and inserts the selected file path.

Resizing Function

def resize():
    image_name = image_entry.get()
    rename = rename_entry.get()
    width = width_entry.get()
    height = height_entry.get()

    if not image_name or not rename or not width or not height:
        messagebox.showerror("Error", "Please fill in all fields.")
        return

    try:
        new_size = (int(width), int(height))
        if ext_var.get() == 1:
            resize_name = rename + ".jpg"
        elif ext_var.get() == 2:
            resize_name = rename + ".png"
        else:
            raise ValueError("Invalid file extension choice.")

        resize_image(image_name, resize_name, new_size)

    except ValueError as e:
        messagebox.showerror("Error", f"Error: {e}. Please enter a valid number.")

This function executes when the user clicks the “Resize Image” button. It retrieves the values from the entry fields and checks for empty inputs, showing an error message if any are empty. It then converts the width and height inputs to integers and constructs the new filename based on the selected extension. Finally, it calls the resize_image function to perform the resizing.

Creating the tkinter GUI

resizer = Tk()
resizer.title("Image Resizer")

Label(resizer, text="Select Image:").grid(row=0, column=0, padx=10, pady=10)
image_entry = Entry(resizer, width=30)
image_entry.grid(row=0, column=1, padx=10, pady=10)
Button(resizer, text="Browse", command=browse_image).grid(row=0, column=2, padx=10, pady=10)

Label(resizer, text="Rename Resized Image:").grid(row=1, column=0, padx=10, pady=10)
rename_entry = Entry(resizer, width=30)
rename_entry.grid(row=1, column=1, padx=10, pady=10)

Label(resizer, text="Choose Extension:").grid(row=2, column=0, padx=10, pady=10)
ext_var = IntVar()
Radiobutton(resizer, text="JPG", variable=ext_var, value=1).grid(row=2, column=1, sticky=W)
Radiobutton(resizer, text="PNG", variable=ext_var, value=2).grid(row=2, column=2, sticky=W)

Label(resizer, text="Width:").grid(row=3, column=0, padx=10, pady=10)
width_entry = Entry(resizer, width=10)
width_entry.grid(row=3, column=1, padx=10, pady=10)

Label(resizer, text="Height:").grid(row=4, column=0, padx=10, pady=10)
height_entry = Entry(resizer, width=10)
height_entry.grid(row=4, column=1, padx=10, pady=10)

Button(resizer, text="Resize Image", command=resize).grid(row=5, column=1, padx=10, pady=10)
resizer.mainloop()

This section initializes the Tkinter application and sets the window title. It creates labels, entry fields, radio buttons for file extension selection, and buttons for browsing and resizing the image. Each GUI element is organized using a grid layout for better visual arrangement. The main loop at the end  keeps the application running until the user closes it.

Output

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top