For AI agents: the complete documentation index is available at https://anyformat.swc.rs/llms.txt, the full documentation bundle is available at https://anyformat.swc.rs/llms-full.txt, and this page is available as Markdown at https://anyformat.swc.rs/guide/python/getting-started.md.

Getting started with Python

Requirements

Python 3.10 or later.

Install a package

Install the package of each format family that you use. The examples on this page use the image family.

pip install anyformat-image

Detect the format of a file

Give the bytes of a file to detect. The function needs only the first bytes of the file. 64 bytes are enough for most image files.

from pathlib import Path

import anyformat_image

anyformat_image.detect(Path("photo.avif").read_bytes())
# => DetectedFormat(format='avif', mime_type='image/avif')

When the format is not recognized, detect returns None.

List the supported formats

supported_formats returns the identifier of each format that detect can return.

import anyformat_image

anyformat_image.supported_formats()
# => ['png', 'jpeg', 'gif', 'webp', 'avif', 'heic', 'jxl', 'tiff', 'bmp', 'ico', 'qoi']

Compare two images

compare_images decodes two PNG files, compares them with the algorithm of pixelmatch, and encodes the diff image.

from pathlib import Path

import anyformat_image

result = anyformat_image.compare_images(
    Path("expected.png").read_bytes(),
    Path("actual.png").read_bytes(),
    threshold=0.1,
    diff=anyformat_image.PngEncodeOptions(),
)
if result.diff_pixels > 0 and result.diff_encoded is not None:
    Path("diff.png").write_bytes(result.diff_encoded)

Next steps