Convert Image to Insta Grid image using Python | Automated Image Processing for Optimal Resizing, Centering, and Tiling

MoneyTech360
By -
0


This script automates image processing tasks using Python's Pillow library. It identifies an image's orientation—square, vertical, or horizontal—and resizes it to specified dimensions, centering the image on a canvas without distorting its aspect ratio. Additionally, it can split a larger image into smaller tiles for efficient loading and display. This is especially useful for web development, graphic design, and content creation, where visual consistency and performance are key. In essence, it's a handy tool for enhancing digital aesthetics and functionality across various applications.





Importing Necessary Libraries:

Python Copy to clipboard
from PIL import Image
import os

These lines import the necessary modules. `PIL` (Python Imaging Library) is a part of the "Pillow" package and is used for opening, manipulating, and saving different image file formats. `os` is a standard Python library that provides a way of using operating system-dependent functionality, like reading or writing to the filesystem.

Determining Image Shape:

Python Copy to clipboard
def determine_image_shape(width, height):
    if width == height:
        return "Square"
    elif height > width:
        return "Vertical"
    else:
        return "Horizontal"
This function determines the shape of an image based on its width and height. It returns "Square" if the width and height are equal, "Vertical" if the height is greater than the width, and "Horizontal" otherwise.

Resizing Image to Fit Canvas:

Python Copy to clipboard
def resize_image(image, canvas_dims):
    img_ratio = image.width / image.height
    canvas_ratio = canvas_dims[0] / canvas_dims[1]

    if img_ratio > canvas_ratio:
        new_width = canvas_dims[0]
        new_height = int(new_width / img_ratio)
    else:
        new_height = canvas_dims[1]
        new_width = int(new_height * img_ratio)

    return image.resize((new_width, new_height), Image.ANTIALIAS)
This function resizes an image to fit within a specified canvas while maintaining the original aspect ratio. It first calculates the aspect ratios of the image and the canvas, then determines the new dimensions for the image so that it fits within the canvas. The image is then resized using these new dimensions with the `ANTIALIAS` filter for high-quality downsampling.

Resizing and Centering the Original Image:

Python Copy to clipboard
def resize_and_center_image(image_path):
    with Image.open(image_path) as img:
        # ... [omitted for brevity]

        # Create a white canvas
        background = Image.new('RGBA', canvas_dims, (255, 255, 255, 255))

        # Resize the image to fit the canvas
        img = resize_image(img, canvas_dims)

        # Calculate coordinates to center the image
        offset = ((canvas_dims[0] - img.width) // 2, (canvas_dims[1] - img.height) // 2)

        # Paste the image on the background
        background.paste(img, offset, img.convert('RGBA'))

        return background
This function opens an image from a given path, determines its shape, and creates a new canvas with the appropriate dimensions. It then resizes the image to fit within the canvas and calculates the coordinates needed to center the image on the canvas. The image is pasted onto the canvas and the resulting image with the original centered on a white background is returned.

Splitting the Image into Tiles:

Python Copy to clipboard
def split_image(image, directory, tile_width=1000, tile_height=1000):
    # If the output directory doesn't exist, create it
    if not os.path.exists(directory):
        os.makedirs(directory)

    img_width, img_height = image.size
    counter = 1

    for top in range(0, img_height, tile_height):
        for left in range(0, img_width, tile_width):
            bottom = min(top + tile_height, img_height)
            right = min(left + tile_width, img_width)

            # Crop the image to the desired tile
            tile = image.crop((left, top, right, bottom))

            tile.save(f"{directory}/tile_{counter}.png")
            counter += 1
This function splits the provided image into tiles, each with the dimensions `tile_width` x `tile_height`. It saves these tiles as separate image files in a specified directory. The function checks if the directory exists, creates it if not, then proceeds to calculate the dimensions for each tile based on the specified width and height. It iterates over the image, extracting tiles using the `crop()` method and saves them with an incremental filename.

Executing the Functions:

Python Copy to clipboard
final_image = resize_and_center_image(r"\\MoneyTech360\Blog\Content\trisha-hot-saree-pics.jpg")
split_image(final_image, "output_tiles")
These lines execute the functions defined above. The `resize_and_center_image()` function is called with the path of the original image, and the result is passed to the `split_image()` function along with the name of the output directory. The image is resized, centered, and then split into tiles, which are saved to the "output_tiles" directory.

Please replace `'\\MoneyTech360\\Blog\\Content\\trisha-hot-saree-pics.jpg'` with the correct path to your image file, and `"output_tiles"` with your desired output directory. The script processes the image as per the described steps and saves the tiles in the specified directory.

Full Code:


Python Copy to clipboard
from PIL import Image
import os

def determine_image_shape(width, height):
    if width == height:
        return "Square"
    elif height > width:
        return "Vertical"
    else:
        return "Horizontal"

def resize_image(image, canvas_dims):
    img_ratio = image.width / image.height
    canvas_ratio = canvas_dims[0] / canvas_dims[1]

    if img_ratio > canvas_ratio:
        # If image width-to-height ratio is greater than canvas, fit to width
        new_width = canvas_dims[0]
        new_height = int(new_width / img_ratio)
    else:
        # If image width-to-height ratio is less than or equal to canvas, fit to height
        new_height = canvas_dims[1]
        new_width = int(new_height * img_ratio)

    return image.resize((new_width, new_height), Image.ANTIALIAS)

def resize_and_center_image(image_path):
    # Open an image file
    with Image.open(image_path) as img:
        width, height = img.size
        shape = determine_image_shape(width, height)

        # Set new canvas dimensions based on the shape
        if shape == "Square":
            canvas_dims = (3000, 3000)
        elif shape == "Vertical":
            canvas_dims = (3000, 5000)
        else:  # Horizontal
            canvas_dims = (3000, 2000)

        # Create a white canvas
        background = Image.new('RGBA', canvas_dims, (255, 255, 255, 255))

        # Resize the image to fit the canvas
        img = resize_image(img, canvas_dims)

        # Calculate coordinates to center the image
        offset = ((canvas_dims[0] - img.width) // 2, (canvas_dims[1] - img.height) // 2)

        # Paste the image on the background
        background.paste(img, offset, img.convert('RGBA')) # ensure transparency if in the original image

        return background

def split_image(image, directory, tile_width=1000, tile_height=1000):
    # If the output directory doesn't exist, create it
    if not os.path.exists(directory):
        os.makedirs(directory)

    img_width, img_height = image.size
    counter = 1

    for top in range(0, img_height, tile_height):
        for left in range(0, img_width, tile_width):
            bottom = min(top + tile_height, img_height)
            right = min(left + tile_width, img_width)

            # Crop the image to the desired tile
            tile = image.crop((left, top, right, bottom))

            tile.save(f"{directory}/name_{counter}.png")
            counter += 1

# Replace 'your_image.png' with your image file's name
final_image = resize_and_center_image(r"\\MoneyTech360\Blog\Content\trisha-hot-saree-pics.jpg")
split_image(final_image, "output_tiles")


Your feedback and suggestion is very valuable for us.
So please comment your thoughts and request code below



Tags:

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!