Python library pygame: Writing image conversion code



Let's create a GUI-based image transformation tool using Pygame and Tkinter. This will allow you to load an image, apply various transformations, and preview the results in a window.



import tkinter as tk
from tkinter import filedialog, messagebox
import pygame
import numpy as np

# --- Configuration ---
pygame.init()

# --- Functions ---
def load_image():
    """Loads an image from a file dialog."""
    global original_image, transformed_image
    filepath = filedialog.askopenfilename(filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.bmp")])
    if filepath:
        try:
            original_image = pygame.image.load(filepath)
            transformed_image = original_image.copy()  # Start with a copy
            update_preview()
        except pygame.error as e:
            messagebox.showerror("Error", f"Error loading image: {e}")

def scale_image():
    """Scales the image."""
    global transformed_image
    try:
        width = int(width_entry.get())
        height = int(height_entry.get())
        transformed_image = pygame.transform.scale(original_image, (width, height))
        update_preview()
    except ValueError:
        messagebox.showerror("Error", "Invalid width or height.")

def rotate_image():
    """Rotates the image."""
    global transformed_image
    try:
        angle = float(angle_entry.get())
        transformed_image = pygame.transform.rotate(original_image, angle)
        update_preview()
    except ValueError:
        messagebox.showerror("Error", "Invalid angle.")

def flip_horizontal():
    """Flips the image horizontally."""
    global transformed_image
    transformed_image = pygame.transform.flip(original_image, True, False)
    update_preview()

def flip_vertical():
    """Flips the image vertically."""
    global transformed_image
    transformed_image = pygame.transform.flip(original_image, False, True)
    update_preview()

def adjust_brightness():
    """Adjusts the brightness of the image."""
    global transformed_image
    try:
        brightness = float(brightness_entry.get())
        image_array = pygame.surfarray.array3d(original_image)
        image_array[:, :, 0] = np.clip(image_array[:, :, 0] + brightness, 0, 255)
        image_array[:, :, 1] = np.clip(image_array[:, :, 1] + brightness, 0, 255)
        image_array[:, :, 2] = np.clip(image_array[:, :, 2] + brightness, 0, 255)
        transformed_image = pygame.surfarray.make_surface(image_array)
        update_preview()
    except ValueError:
        messagebox.showerror("Error", "Invalid brightness value.")

def update_preview():
    """Updates the Pygame preview window."""
    if transformed_image:
        screen.blit(transformed_image, (0, 0))
        pygame.display.flip()

# --- GUI Setup ---
root = tk.Tk()
root.title("Image Transformation Tool")

# Load Image Button
load_button = tk.Button(root, text="Load Image", command=load_image)
load_button.pack(pady=10)

# Scaling Controls
scale_label = tk.Label(root, text="Scale:")
scale_label.pack()
width_label = tk.Label(root, text="Width:")
width_label.pack()
width_entry = tk.Entry(root)
width_entry.pack()
height_label = tk.Label(root, text="Height:")
height_label.pack()
height_entry = tk.Entry(root)
height_entry.pack()
scale_button = tk.Button(root, text="Scale", command=scale_image)
scale_button.pack(pady=5)

# Rotation Controls
rotate_label = tk.Label(root, text="Rotate:")
rotate_label.pack()
angle_label = tk.Label(root, text="Angle (degrees):")
angle_label.pack()
angle_entry = tk.Entry(root)
angle_entry.pack()
rotate_button = tk.Button(root, text="Rotate", command=rotate_image)
rotate_button.pack(pady=5)

# Flip Controls
flip_horizontal_button = tk.Button(root, text="Flip Horizontal", command=flip_horizontal)
flip_horizontal_button.pack()
flip_vertical_button = tk.Button(root, text="Flip Vertical", command=flip_vertical)
flip_vertical_button.pack()

# Brightness Controls
brightness_label = tk.Label(root, text="Brightness:")
brightness_label.pack()
brightness_entry = tk.Entry(root)
brightness_entry.pack()
brightness_button = tk.Button(root, text="Adjust Brightness", command=adjust_brightness)
brightness_button.pack(pady=5)

# Pygame Preview Window
screen = pygame.display.set_mode((600, 400))  # Initial size
pygame.display.set_caption("Image Preview")

# Initial Variables
original_image = None
transformed_image = None

# --- Main Loop ---
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    root.update()  # Update Tkinter GUI

    if transformed_image:
        update_preview()

pygame.quit()
root.destroy()
@

Explanation:

Imports: Imports necessary libraries (Tkinter, Pygame, NumPy).

Functions:

  • load_image(): Loads an image using a file dialog.

  • scale_image(): Scales the image based on user input.

  • rotate_image(): Rotates the image based on user input.

  • flip_horizontal()/flip_vertical(): Flips the image horizontally or vertically.

  • adjust_brightness(): Adjusts the brightness of the image.

  • update_preview(): Updates the Pygame preview window with the transformed image.

GUI Setup:

Creates the main Tkinter window.

Adds buttons and entry fields for each transformation.

Pygame Preview Window:

Creates a Pygame window for displaying the transformed image.

Main Loop:

Handles events (e.g., closing the window).

Updates the Tkinter GUI using root.update().

Updates the Pygame preview window using update_preview().

How to Run:

Make sure you have Pygame, Tkinter, and NumPy installed:


pip install pygame
pip install tkinter 
pip install numpy

@

Save the code as a .py file (e.g., image_transformer.py).

Run the file from your terminal: 

>py image_transformer.py

Important Notes:

Error Handling: The code includes basic error handling, but you can add more robust error handling to handle various scenarios.

GUI Layout: You can customize the GUI layout using Tkinter's layout managers (e.g., pack, grid, place).

More Transformations: You can add more transformations by creating new functions and adding corresponding controls to the GUI.

Performance: For very large images, the transformations might be slow. Consider optimizing the code or using a more efficient image processing library.

Comments