Creating an Image Resizer in Tkinter

In this tutorial, we will create a simple yet effective image resizer application using Tkinter, Python’s built-in GUI toolkit. Image resizing is a common task that can be useful for various purposes, such as preparing images for websites, social media, or printing.

With this application, users will be able to easily select an image, specify the desired dimensions, and resize the image with just a few clicks. We’ll leverage the Pillow library for image processing, which will enable us to handle various image formats and perform resizing operations smoothly.

Throughout this tutorial, you’ll learn how to set up the Tkinter interface, work with image files, and implement the resizing functionality. By the end, you’ll have a functional image resizer and a solid understanding of how to combine GUI programming with image manipulation in Python.

Let’s get started!

In the context of creating an image resizer in Tkinter, you primarily use the following package:

  • Tkinter: This is the standard GUI toolkit for Python, which is used for creating the graphical user interface.
  • Pillow (PIL): This is a powerful imaging library that allows you to open, manipulate, and save image files. It is used in the example for handling image resizing and displaying images in the Tkinter canvas.

Create an Image Resizer in Tkinter:

To create an image resizer in Tkinter, you need to follow these basic steps:

  1. Set Up the Environment:
    • Install Python and the Pillow library:
      pip install Pillow
  2. Import Required Libraries:
    • Import Tkinter and Pillow in your script.
  3. Create the Main Application Class:
    • Define a class to encapsulate the application’s functionality.
  4. Build the User Interface:
    • Add labels, entry fields, and buttons for user interaction.
    • Create a canvas to display images.
  5. Implement Image Selection:
    • Create a method to open a file dialog for selecting an image.
  6. Handle Image Resizing:
    • Implement a method to resize the selected image based on user inputs.
  7. Display the Resized Image:
    • Update the canvas to show the resized image.
  8. Run the Application:
    • Use mainloop() to start the Tkinter event loop.
  9. Test the Application:
    • Verify the functionality by selecting an image and resizing it.

Example for creating an image resizer in Tkinter:

import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk

class ImageResizerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Image Resizer")

        self.image = None
        self.tk_image = None

        # Create UI components
        self.label = tk.Label(root, text="Select an image to resize:")
        self.label.pack(pady=10)

        self.select_button = tk.Button(root, text="Select Image", command=self.select_image)
        self.select_button.pack(pady=5)

        self.width_label = tk.Label(root, text="Width:")
        self.width_label.pack(pady=5)

        self.width_entry = tk.Entry(root)
        self.width_entry.pack(pady=5)

        self.height_label = tk.Label(root, text="Height:")
        self.height_label.pack(pady=5)

        self.height_entry = tk.Entry(root)
        self.height_entry.pack(pady=5)

        self.resize_button = tk.Button(root, text="Resize Image", command=self.resize_image)
        self.resize_button.pack(pady=10)

        self.canvas = tk.Canvas(root, width=300, height=300)
        self.canvas.pack(pady=10)

    def select_image(self):
        file_path = filedialog.askopenfilename(title="Select an image", filetypes=[("Image files", "*.jpg;*.jpeg;*.png;*.gif")])
        if file_path:
            self.image = Image.open(file_path)
            self.display_image(self.image)

    def display_image(self, image):
        self.tk_image = ImageTk.PhotoImage(image)
        self.canvas.create_image(150, 150, image=self.tk_image, anchor=tk.CENTER)

    def resize_image(self):
        if self.image:
            try:
                width = int(self.width_entry.get())
                height = int(self.height_entry.get())
                resized_image = self.image.resize((width, height), Image.ANTIALIAS)
                self.display_image(resized_image)
                
                # Save resized image (optional)
                resized_image.save("resized_image.png")
                messagebox.showinfo("Success", "Image resized and saved as 'resized_image.png'")
            except ValueError:
                messagebox.showerror("Error", "Please enter valid width and height values.")
        else:
            messagebox.showerror("Error", "No image selected.")

if __name__ == "__main__":
    root = tk.Tk()
    app = ImageResizerApp(root)
    root.mainloop()

 

How to Use the Code:

  1. Set Up Environment: Ensure you have Python installed along with the Tkinter and Pillow libraries.
  2. Run the Program: Copy and paste the code into a Python file (e.g., image_resizer.py) and run it.
  3. Select an Image: Click the “Select Image” button to choose an image file from your computer.
  4. Enter Dimensions: Enter the desired width and height in the provided fields.
  5. Resize the Image: Click the “Resize Image” button to resize and save the image as resized_image.png.

This program provides a simple yet functional interface for resizing images. You can expand its capabilities by adding more features like maintaining aspect ratio, different file formats, or additional image editing options.

Example Output Screens
  • Initial Window:
+--------------------------------------+
| Select an image to resize:          |
| [Select Image]                      |
| Width: [__________]                 |
| Height: [__________]                |
| [Resize Image]                      |
|                                      |
|               [Canvas]              |
+--------------------------------------+
  • Resized Image Display:
+--------------------------------------+
| Select an image to resize: |
| [Select Image] |
| Width: [200] |
| Height: [150] |
| [Resize Image] |
| |
| [Resized Image Display] |
+--------------------------------------+
  • Success Message:
+----------------------+
| Image resized and |
| saved as 'resized_image.png' |
+----------------------+

This is what you can expect as the output when using the image resizer application created with Tkinter.

Conclusion:

Following these steps will help you create a functional image resizer application using Tkinter. You can expand on this foundation by adding more features, such as maintaining aspect ratio, supporting additional image formats, or enhancing the user interface.

 

Leave a Comment

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

Scroll to Top