imgutils.data.pad

Image padding and resizing utilities.

This module provides functions for padding and resizing images to specified dimensions while maintaining aspect ratio. It includes utilities for parsing size specifications, color values, and handling different image modes.

pad_image_to_size

imgutils.data.pad.pad_image_to_size(pic: str | PathLike | bytes | bytearray | BinaryIO | Image, size: int | Tuple[int, int], background_color: str | int | Tuple[int, int, int] | Tuple[int, int, int, int] = 'white', interpolation: int = 2)[source]

Resize and pad an image to the specified size while maintaining aspect ratio.

The function first resizes the image to fit within the target dimensions while preserving the aspect ratio, then pads the result with the specified background color to reach the exact target size.

Parameters:
  • pic (ImageTyping) – Input image (PIL Image, file path, or other supported format)

  • size (Union[int, Tuple[int, int]]) – Target size as an integer or tuple of (width, height)

  • background_color (Union[str, int, Tuple[int, int, int], Tuple[int, int, int, int]]) – Color to use for padding (name, RGB tuple, etc.)

  • interpolation (int) – PIL interpolation method for resizing

Returns:

Resized and padded image

Return type:

PIL.Image.Image

Example:

>>> from PIL import Image
>>> img = Image.new('RGB', (100, 50))
>>> padded = pad_image_to_size(img, (200, 200), background_color='blue')
>>> padded.size
(200, 200)