CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pillow

Python Imaging Library (Fork) providing comprehensive image processing capabilities for reading, writing, and manipulating images across dozens of formats.

Pending
Overview
Eval results
Files

core-image.mddocs/

Core Image Operations

Essential image manipulation functions that form the foundation of Pillow's image processing capabilities. These operations handle the fundamental tasks of opening, creating, transforming, and saving images across multiple formats.

Capabilities

Image Creation and Loading

Create new images or load existing images from files, bytes, or other data sources.

def new(mode, size, color=0):
    """
    Creates a new image with the given mode and size.

    Parameters:
    - mode (str): The mode to use for the new image (e.g., "RGB", "RGBA", "L")
    - size (tuple): Size tuple (width, height)
    - color (int | tuple | str): Color to use for the image. Default is 0 (black)

    Returns:
    Image: A new Image object
    """

def open(fp, mode="r", formats=None):
    """
    Opens and identifies an image file.

    Parameters:
    - fp (str | Path | file): Filename, pathlib.Path object, or file object
    - mode (str): Mode for opening the file ("r" for reading)
    - formats (list): List of format names to attempt

    Returns:
    Image: An Image object

    Raises:
    UnidentifiedImageError: If the image cannot be opened
    IOError: If the file cannot be found or opened
    """

def frombytes(mode, size, data, decoder_name="raw", *args):
    """
    Creates an image from bytes data.

    Parameters:
    - mode (str): The image mode
    - size (tuple): Size tuple (width, height)
    - data (bytes): Raw image data
    - decoder_name (str): Decoder to use

    Returns:
    Image: A new Image object
    """

def fromarray(obj, mode=None):
    """
    Creates an image from an array-like object.

    Parameters:
    - obj: Array-like object (numpy array, etc.)
    - mode (str): Image mode to use

    Returns:
    Image: A new Image object
    """

Image Properties and Information

Access image metadata and properties.

class Image:
    @property
    def size(self) -> tuple[int, int]:
        """Image size as (width, height) tuple."""

    @property
    def width(self) -> int:
        """Image width in pixels."""

    @property
    def height(self) -> int:
        """Image height in pixels."""

    @property
    def mode(self) -> str:
        """Image mode (e.g., "RGB", "RGBA", "L")."""

    @property
    def format(self) -> str | None:
        """Original format of the image file."""

    @property
    def info(self) -> dict:
        """Dictionary containing image metadata."""

    def getbands(self) -> tuple[str, ...]:
        """
        Returns the names of the bands in the image.

        Returns:
        tuple: Band names
        """

    def getbbox(self) -> tuple[int, int, int, int] | None:
        """
        Calculates the bounding box of non-zero regions.

        Returns:
        tuple | None: Bounding box as (left, top, right, bottom) or None
        """

    def getextrema(self) -> tuple | tuple[tuple, ...]:
        """
        Gets the minimum and maximum pixel values.

        Returns:
        tuple: Min/max values for each band
        """

Geometric Transformations

Transform images through resizing, rotation, cropping, and other geometric operations.

class Image:
    def resize(self, size, resample=None, box=None, reducing_gap=None):
        """
        Returns a resized copy of this image.

        Parameters:
        - size (tuple): Target size as (width, height)
        - resample (int): Resampling filter (Resampling.NEAREST, .BILINEAR, .BICUBIC, .LANCZOS)
        - box (tuple): Region to resize from as (left, top, right, bottom)
        - reducing_gap (float): Optimization for downscaling

        Returns:
        Image: Resized image
        """

    def rotate(self, angle, resample=0, expand=0, center=None, translate=None, fillcolor=None):
        """
        Returns a rotated copy of this image.

        Parameters:
        - angle (float): Rotation angle in degrees (counter-clockwise)
        - resample (int): Resampling filter
        - expand (bool): If True, expands output to fit entire rotated image
        - center (tuple): Center of rotation as (x, y)
        - translate (tuple): Post-rotation translation as (x, y)
        - fillcolor (int | tuple | str): Color for areas outside original image

        Returns:
        Image: Rotated image
        """

    def crop(self, box=None):
        """
        Returns a rectangular region from this image.

        Parameters:
        - box (tuple): Crop rectangle as (left, top, right, bottom)

        Returns:
        Image: Cropped image
        """

    def thumbnail(self, size, resample=3, reducing_gap=2.0):
        """
        Make this image into a thumbnail (modifies image in place).

        Parameters:
        - size (tuple): Maximum size as (width, height)
        - resample (int): Resampling filter
        - reducing_gap (float): Optimization for downscaling
        """

    def transpose(self, method):
        """
        Transpose image (flip or rotate in 90-degree steps).

        Parameters:
        - method (int): Transpose method (Transpose.FLIP_LEFT_RIGHT, etc.)

        Returns:
        Image: Transposed image
        """

Color and Mode Operations

Convert between color modes and manipulate color properties.

class Image:
    def convert(self, mode=None, matrix=None, dither=None, palette=0, colors=256):
        """
        Returns a converted copy of this image.

        Parameters:
        - mode (str): Target mode ("L", "RGB", "RGBA", "CMYK", etc.)
        - matrix (sequence): Conversion matrix for "RGB" to "L" conversion
        - dither (int): Dithering method (Dither.NONE, .ORDERED, .FLOYDSTEINBERG)
        - palette (int): Palette mode (Palette.WEB, .ADAPTIVE)
        - colors (int): Number of colors for palette conversion

        Returns:
        Image: Converted image
        """

    def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1):
        """
        Convert image to 'P' mode with specified number of colors.

        Parameters:
        - colors (int): Number of colors in result (2-256)
        - method (int): Quantization method (Quantize.MEDIANCUT, etc.)
        - kmeans (int): K-means iteration count
        - palette (Image): Palette image to use
        - dither (int): Dithering method

        Returns:
        Image: Quantized image
        """

    def split(self):
        """
        Split image into individual bands.

        Returns:
        tuple: Tuple of single-band images
        """

    def getchannel(self, channel):
        """
        Returns an image containing a single channel.

        Parameters:
        - channel (int | str): Band index or name

        Returns:
        Image: Single-channel image
        """

Image I/O Operations

Save images to files or get image data as bytes.

class Image:
    def save(self, fp, format=None, **params):
        """
        Saves this image under the given filename.

        Parameters:
        - fp (str | Path | file): Target filename, pathlib.Path, or file object
        - format (str): Image format ("JPEG", "PNG", "TIFF", etc.)
        - **params: Format-specific parameters

        Raises:
        ValueError: If format cannot be determined
        IOError: If the file cannot be written
        """

    def tobytes(self, encoder_name="raw", *args):
        """
        Return image as bytes.

        Parameters:
        - encoder_name (str): Encoder to use
        - *args: Encoder arguments

        Returns:
        bytes: Image data
        """

    def tobitmap(self, name="image"):
        """
        Returns the image converted to an X11 bitmap.

        Parameters:
        - name (str): Name to use in bitmap

        Returns:
        bytes: X11 bitmap data
        """

Multi-frame Image Support

Handle animated images and image sequences.

class Image:
    @property
    def is_animated(self) -> bool:
        """True if image has multiple frames."""

    @property
    def n_frames(self) -> int:
        """Number of frames in image."""

    def seek(self, frame):
        """
        Seeks to a specific frame in a multi-frame image.

        Parameters:
        - frame (int): Frame number to seek to
        """

    def tell(self) -> int:
        """
        Returns the current frame number.

        Returns:
        int: Current frame number
        """

Pixel Access and Manipulation

Direct pixel-level access and manipulation.

class Image:
    def getpixel(self, xy):
        """
        Returns the pixel value at a given position.

        Parameters:
        - xy (tuple): Coordinate tuple (x, y)

        Returns:
        int | tuple: Pixel value
        """

    def putpixel(self, xy, value):
        """
        Modifies the pixel at a given position.

        Parameters:
        - xy (tuple): Coordinate tuple (x, y)
        - value (int | tuple): New pixel value
        """

    def point(self, lut, mode=None):
        """
        Maps image through lookup table or function.

        Parameters:
        - lut (sequence | function): Lookup table or mapping function
        - mode (str): Output image mode

        Returns:
        Image: Mapped image
        """

    def paste(self, im, box=None, mask=None):
        """
        Pastes another image into this image.

        Parameters:
        - im (Image | int | tuple | str): Source image or color
        - box (tuple): Target region as (left, top) or (left, top, right, bottom)
        - mask (Image): Optional mask image
        """

Utility Functions

Helper functions for image processing.

def merge(mode, bands):
    """
    Merge a set of single-band images into a multi-band image.

    Parameters:
    - mode (str): Mode of output image
    - bands (sequence): Sequence of single-band images

    Returns:
    Image: Multi-band image
    """

def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images.

    Parameters:
    - im1 (Image): First image
    - im2 (Image): Second image
    - alpha (float): Interpolation factor (0.0 to 1.0)

    Returns:
    Image: Blended image
    """

def composite(image1, image2, mask):
    """
    Create composite image using transparency mask.

    Parameters:
    - image1 (Image): First image
    - image2 (Image): Second image  
    - mask (Image): Mask image

    Returns:
    Image: Composite image
    """

def alpha_composite(im1, im2):
    """
    Alpha composite two RGBA images.

    Parameters:
    - im1 (Image): First RGBA image
    - im2 (Image): Second RGBA image

    Returns:
    Image: Composite RGBA image
    """

Usage Examples

Basic Image Processing Pipeline

from PIL import Image

# Open and process an image
with Image.open("input.jpg") as img:
    # Get image info
    print(f"Original size: {img.size}, mode: {img.mode}")
    
    # Convert to RGB if needed
    if img.mode != "RGB":
        img = img.convert("RGB")
    
    # Resize maintaining aspect ratio
    img.thumbnail((800, 600), Image.Resampling.LANCZOS)
    
    # Rotate the image
    rotated = img.rotate(45, expand=True, fillcolor="white")
    
    # Save with quality setting
    rotated.save("output.jpg", "JPEG", quality=85, optimize=True)

Working with Image Channels

from PIL import Image

# Load an RGB image
img = Image.open("color_image.jpg")

# Split into individual channels
r, g, b = img.split()

# Process individual channels
enhanced_red = r.point(lambda x: x * 1.2)  # Brighten red channel

# Merge channels back
enhanced = Image.merge("RGB", [enhanced_red, g, b])

# Or get a single channel
red_only = img.getchannel("R")
red_only.save("red_channel.jpg")

Creating Images from Data

from PIL import Image
import numpy as np

# Create from numpy array
data = np.random.rand(100, 100, 3) * 255
img = Image.fromarray(data.astype('uint8'), 'RGB')

# Create new blank image
blank = Image.new("RGBA", (400, 300), (255, 255, 255, 128))

# Create gradient
width, height = 256, 256
gradient = Image.new("L", (width, height))
for x in range(width):
    for y in range(height):
        gradient.putpixel((x, y), x)

Install with Tessl CLI

npx tessl i tessl/pypi-pillow

docs

color-management.md

color-utilities.md

core-image.md

drawing.md

enhancement.md

filters.md

fonts.md

image-sequences.md

image-statistics.md

index.md

math-operations.md

operations.md

tile.json