List of Topics:
Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Resize and Crop an Image Using the Pillow Library in Python?

Resizing and Cropping Images with Pillow

Condition for Resizing and Cropping Images with Pillow in Python

  • Description:
    The Pillow library in Python allows for easy image manipulation, including resizing and cropping. Resizing changes image dimensions, while cropping focuses on specific sections. These techniques are widely used in machine learning, web optimization, and enhancing visual content in digital projects.
Why Should We Choose Pillow?
  • Ease of Use: Straightforward API for image manipulation.
  • Open Source: Free and open-source, suitable for all projects.
  • Compatibility: Supports formats like PNG, JPEG, BMP, and TIFF.
  • Flexibility: Enables advanced processing like filtering and rotation.
Step by Step Process
  • Import the Library: Import the PIL.Image module from Pillow.
  • Load the Image: Use `Image.open()` to load an image.
  • Resize the Image: Change the size using `image.resize()`.
  • Crop the Image: Focus on a region using `image.crop()`.
  • Save the Image: Save the modified image with `image.save()`.
Sample Source Code
  • from PIL import Image, ImageEnhance, ImageFilter
    import os

    # Define folder paths
    image_folder = '/path/to/images'
    output_dir = '/path/to/processed'

    # Create output directory if not exists
    if not os.path.exists(output_dir):
     os.makedirs(output_dir)

    # Get image files
    image_files = [f for f in os.listdir(image_folder) if f.endswith(('.png', '.jpg', '.jpeg'))]

    # Process each image
    for image_name in image_files:
     image_path = os.path.join(image_folder, image_name)
     with Image.open(image_path) as img:
      # Resize and crop
      resized_img = img.resize((300, 300))
      cropped_img = img.crop((0, 0, 200, 200))

      # Save results
      resized_img.save(os.path.join(output_dir, f"resized_{image_name}"))
      cropped_img.save(os.path.join(output_dir, f"cropped_{image_name}"))

    print("Processing completed!")
Screenshots
  • Pillow Resizing and Cropping Output