python LogoImage Manipulation with Pillow

Image manipulation refers to the process of altering or transforming a digital image using software. This can involve a wide range of operations, from basic adjustments like resizing and cropping to more complex tasks such as color correction, applying artistic filters, or compositing multiple images. In Python, the Pillow library is the de facto standard for working with images. It is a user-friendly fork of the classic Python Imaging Library (PIL) and provides powerful image processing capabilities.

Pillow allows developers to perform various operations, including:
- Opening and Saving: Load images from various file formats (JPEG, PNG, GIF, BMP, etc.) and save them in different formats.
- Resizing and Cropping: Change the dimensions of an image or extract a specific region.
- Rotation and Flipping: Rotate an image by a specified angle or flip it horizontally/vertically.
- Color Conversions: Convert images between different color modes (e.g., RGB, grayscale, CMYK).
- Filters and Enhancements: Apply built-in filters (e.g., blur, sharpen, emboss) or adjust brightness, contrast, and color balance.
- Drawing: Add text, lines, rectangles, and other shapes to images.
- Pixel Access: Directly access and manipulate individual pixel data.
- Compositing: Overlay images or blend them together.

Pillow is an essential tool for tasks like web development (thumbnail generation, watermarking), data science (image preprocessing for machine learning), and general automation involving image assets. To use Pillow, it first needs to be installed via pip: `pip install Pillow`.

Example Code

from PIL import Image, ImageFilter, ImageDraw, ImageFont
import os

 --- 1. Prepare an example image ---
 For demonstration, we'll create a simple white image if 'input.jpg' doesn't exist.
 In a real scenario, you would replace 'input.jpg' with your actual image path.
input_image_path = "input.jpg"
output_resize_path = "output_resized.jpg"
output_rotate_path = "output_rotated.jpg"
output_filter_path = "output_filtered.jpg"
output_text_path = "output_text.jpg"

if not os.path.exists(input_image_path):
    print(f"'{input_image_path}' not found. Creating a dummy image for demonstration.")
    dummy_image = Image.new('RGB', (400, 300), color = 'white')
    draw = ImageDraw.Draw(dummy_image)
     Try to add some text if a font is available
    try:
         Using a common font path for demonstration; adjust if needed
        font_path = "arial.ttf"  Or any other .ttf font file
        if os.path.exists(font_path):
            font = ImageFont.truetype(font_path, 40)
            draw.text((50, 120), "Hello Pillow!", fill="red", font=font)
        else:
            print(f"Warning: Font '{font_path}' not found. Text will be drawn with default font.")
            draw.text((50, 120), "Hello Pillow!", fill="red")
    except Exception as e:
        print(f"Error drawing text with truetype font: {e}. Drawing with default font.")
        draw.text((50, 120), "Hello Pillow!", fill="red")

    dummy_image.save(input_image_path)
    print(f"Dummy image saved as '{input_image_path}'.")
else:
    print(f"Using existing image '{input_image_path}'.")


 --- 2. Open an image ---
try:
    img = Image.open(input_image_path)
    print(f"Original image size: {img.size}")
    img.show(title="Original Image")  Opens the image in your default viewer
except FileNotFoundError:
    print(f"Error: The file '{input_image_path}' was not found. Please ensure it exists.")
    exit()
except Exception as e:
    print(f"An error occurred while opening the image: {e}")
    exit()

 --- 3. Resize an image ---
 New size: width=200, height=150
resized_img = img.resize((200, 150))
resized_img.save(output_resize_path)
print(f"Resized image saved as '{output_resize_path}'. New size: {resized_img.size}")
 resized_img.show(title="Resized Image")

 --- 4. Rotate an image ---
 Rotate by 45 degrees, expanding the canvas to fit the entire rotated image
rotated_img = img.rotate(45, expand=True)
rotated_img.save(output_rotate_path)
print(f"Rotated image saved as '{output_rotate_path}'. New size: {rotated_img.size}")
 rotated_img.show(title="Rotated Image")

 --- 5. Apply a filter (e.g., Gaussian Blur) ---
filtered_img = img.filter(ImageFilter.GaussianBlur(radius=5))
filtered_img.save(output_filter_path)
print(f"Filtered image (Gaussian Blur) saved as '{output_filter_path}'.")
 filtered_img.show(title="Filtered Image")

 --- 6. Add text to an image ---
text_img = img.copy()  Create a copy to avoid modifying the original
draw = ImageDraw.Draw(text_img)
text = "Pillow Power!"
fill_color = (255, 0, 0)  Red color
position = (10, 10)  Top-left corner

 Try to load a font. If not found, use a default (often much smaller).
try:
     Adjust font path if 'arial.ttf' is not found on your system
     Common paths: Windows: C:\\Windows\\Fonts\\arial.ttf, Linux: /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
    font = ImageFont.truetype("arial.ttf", 36)
except IOError:
    print("Could not load truetype font. Using default PIL font.")
    font = ImageFont.load_default()

draw.text(position, text, fill=fill_color, font=font)
text_img.save(output_text_path)
print(f"Image with text saved as '{output_text_path}'.")
 text_img.show(title="Image with Text")

print("\nAll operations completed. Check the output files in your directory.")
print("You might need to install 'tkinter' or 'ImageMagick' for .show() method to work on some systems.")