Python Image and Video Libraries

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Baseline date: 2026-10-07. Versions are the latest on PyPI on that date: Pillow 12.3.0, pillow-heif 1.8.0, pillow-avif-plugin 1.6.0, pyvips 3.2.0, MoviePy 2.2.1, blurhash-python 1.2.2. Check the release notes of the exact versions you install, since format support depends on how the wheels were built. The code on this page was run with Python 3.13, Pillow 13.0.0 (released on 2026-10-16, after the baseline date), pillow-heif 1.8.1, pyvips 3.2.0 with its bundled libvips 8.18.7, blurhash-python 1.2.2 and MoviePy 2.2.1; FFmpeg was 6.1.1 from Ubuntu 24.04.

Image libraries

Library Licence Notes

Pillow

MIT-CMU (HPND style)

The standard imaging library. JPEG, PNG, WebP, GIF, TIFF. AVIF read and write is built in from Pillow 11.3 when the wheel includes libavif, so check features.check("avif"). Pure Python API over C code.

pillow-heif

BSD-3-Clause

Adds HEIF and HEIC (and AVIF) reading and writing to Pillow, using libheif. Needed to read iPhone uploads.

pillow-avif-plugin

MIT

AVIF support for older Pillow versions. Treat it as a stopgap: with a current Pillow, use the built-in AVIF support.

pyvips

MIT

Binding to libvips. Lower memory and higher throughput than Pillow on big images, because it streams. Needs libvips installed, or the binary wheel.

Pillow: thumbnails, formats and EXIF

pip install Pillow pillow-heif
from PIL import Image, ImageOps, features
from pillow_heif import register_heif_opener

register_heif_opener()                      # lets Image.open read HEIC and HEIF

def make_variants(src: str, out_dir: str, widths=(320, 640, 1280)) -> list[str]:
    written = []
    with Image.open(src) as im:
        im = ImageOps.exif_transpose(im)    # apply the orientation, then drop the tag
        im = im.convert("RGB")              # sRGB, no alpha, no palette
        for width in widths:
            if width >= im.width:
                width = im.width            # never upscale
            height = round(im.height * width / im.width)
            resized = im.resize((width, height), Image.Resampling.LANCZOS)
            resized.save(f"{out_dir}/w{width}.jpg", "JPEG", quality=80, optimize=True, progressive=True)
            resized.save(f"{out_dir}/w{width}.webp", "WEBP", quality=78, method=5)
            written += [f"w{width}.jpg", f"w{width}.webp"]
            if features.check("avif"):
                resized.save(f"{out_dir}/w{width}.avif", "AVIF", quality=60, speed=6)
                written.append(f"w{width}.avif")
    return written

Image.thumbnailw, h resizes in place keeping the aspect ratio, and ImageOps.fit crops to an exact aspect ratio. A width that is not below the image width is clamped to it, so a small original gets one variant at its own size (two clamped widths would write the same file twice, which process below avoids by using a set). Image.open is lazy, and Pillow protects against decompression bombs with Image.MAX_IMAGE_PIXELS: leave the limit on and catch DecompressionBombError. Saving a Pillow image without passing exif= drops the EXIF block, which is how metadata gets stripped. For a colour profile, convert with ImageCms to sRGB before saving.

pyvips

import pyvips

def avif_variant(src: str, dst: str, width: int) -> None:
    # thumbnail() shrinks on load, so it is much cheaper than open-then-resize.
    image = pyvips.Image.thumbnail(src, width, height=10_000_000, size="down")   # width bound only
    image.write_to_file(dst, Q=60, effort=5, keep="none")

keep="none" drops all metadata (libvips 8.15 and later; strip=True is the older spelling and still worked in the 8.18 build bundled with pyvips 3.2). Like the command line tool, thumbnail takes a box: the second positional argument is the width and height defaults to the same value, hence the very large height to bound the width only. size="down" never enlarges: asked for 5000 pixels on the 2400 pixel cover it returned 2400 by 3600, and without it 5000 by 7500. Without keep="none" the AVIF from the phone file would carry its GPS tags: the default JPEG output kept exif-ifd0-Make and the exif-ifd3-GPS* fields.

Reference: pyvips documentation.

BlurHash

pip install blurhash-python
import blurhash
from PIL import Image

with Image.open("original.jpg") as im:
    im = im.convert("RGB").resize((64, 96), Image.Resampling.BILINEAR)   # downscale first, 2:3 like the cover
    hash_ = blurhash.encode(im, x_components=3, y_components=4)          # 3 columns, 4 rows: 28 characters

The blurhash-python package from the woltapp repository accepts a Pillow image or a file object. The blurhash package on PyPI is the other implementation, and has a different call signature (it takes a list of pixel rows), so check the README of the one you install. References: woltapp/blurhash-python and halcy/blurhash-python. The algorithm is described in the BlurHash page.

A complete cover job

The running example is the Moby-Dick cover with id b81f, uploaded from a phone as a 3600 by 2400 JPEG with EXIF orientation 6 and a GPS block. The module below does what the upload worker does for one file: it checks the header and the pixel count before decoding, rejects formats that are not on the allow list, applies the orientation, converts embedded profiles to sRGB, writes AVIF, WebP and JPEG variants at 320, 640 and 1280 pixels, and encodes a 3 by 4 BlurHash from a 64 by 96 thumbnail.

# media_pipeline.py: variants plus BlurHash for one upload, the record the media API returns
import io, json, time, uuid
from dataclasses import dataclass
import blurhash
from PIL import Image, ImageCms, ImageOps, features
from pillow_heif import register_heif_opener

register_heif_opener()
ALLOWED = {"JPEG", "PNG", "WEBP", "HEIF"}
MAX_PIXELS = 60_000_000                      # about 7750 x 7750
SRGB = ImageCms.createProfile("sRGB")
Image.MAX_IMAGE_PIXELS = MAX_PIXELS          # Pillow warns above this and raises above twice this value

class Rejected(Exception):
    pass

def open_checked(data: bytes) -> Image.Image:
    try:
        with Image.open(io.BytesIO(data)) as probe:
            probe.verify()                   # header and checksums only, nothing is decoded
            fmt, size = probe.format, probe.size
    except (OSError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
        raise Rejected(f"not a decodable image: {exc}") from exc
    if fmt not in ALLOWED:
        raise Rejected(f"format {fmt} is not accepted")
    if size[0] * size[1] > MAX_PIXELS:
        raise Rejected(f"{size[0]}x{size[1]} exceeds the pixel cap")
    return Image.open(io.BytesIO(data))      # verify() leaves the first object unusable

def to_srgb(im: Image.Image) -> Image.Image:
    icc = im.info.get("icc_profile")
    if icc:
        src = ImageCms.ImageCmsProfile(io.BytesIO(icc))
        im = ImageCms.profileToProfile(im.convert("RGB"), src, SRGB, outputMode="RGB")
    return im.convert("RGB")

def process(data: bytes, widths=(320, 640, 1280)) -> dict:
    with open_checked(data) as im:
        im = to_srgb(ImageOps.exif_transpose(im))       # pixels rotated, tag gone, sRGB, no alpha
        record = {"id": uuid.uuid4().hex[:4], "width": im.width, "height": im.height, "variants": []}
        for width in sorted({min(w, im.width) for w in widths}):
            height = round(im.height * width / im.width)
            resized = im.resize((width, height), Image.Resampling.LANCZOS)
            outputs = [("jpeg", "jpg", dict(quality=80, optimize=True, progressive=True)),
                       ("webp", "webp", dict(quality=78, method=5))]
            if features.check("avif"):
                outputs.insert(0, ("avif", "avif", dict(quality=60, speed=6)))
            for fmt, ext, opts in outputs:
                buf = io.BytesIO()
                resized.save(buf, fmt.upper(), **opts)              # no exif= argument, so no metadata
                key = f"covers/{record['id']}/w{width}.{ext}"
                record["variants"].append({"format": fmt, "width": width, "bytes": buf.tell(), "key": key})
        thumb = im.resize((64, 96), Image.Resampling.BILINEAR)      # 2:3, so 3 x 4 components
        record["blurhash"] = blurhash.encode(thumb, x_components=3, y_components=4)
    return record

On the phone file it returns this record (the three formats per width, abbreviated here to the sizes):

Width AVIF WebP JPEG

320 x 480

6,680 B

11,376 B

18,200 B

640 x 960

12,664 B

24,354 B

47,365 B

1280 x 1920

25,167 B

47,050 B

119,105 B

The record’s width and height are 2400 and 3600 (the rotated size), and its blurhash is TKAeBpR,9GiXf8WC0Lt6?GN1j[t6. All nine files plus the hash took about 435 ms on a laptop, in a single thread. None of the files has EXIF, because save was called without an exif= argument. The same function behaved like this on other inputs:

Input Result

HEIC, 1200 by 1800 (written with pillow-heif)

Accepted: the register_heif_opener() call at the top of the module makes Image.open read it, and nine variants came out

GIF

Rejected: format GIF is not accepted

64 bytes of zeros

Rejected: not a decodable image

PNG of 20000 by 20000 pixels (388 KB on disk)

Rejected, with Pillow’s message that 400000000 pixels exceed the limit of 120000000 (twice MAX_IMAGE_PIXELS)

PNG of 9000 by 9000 pixels

Rejected: 9000x9000 exceeds the pixel cap from the explicit check (81 million pixels is above the cap of 60 million but below twice the cap, where Pillow only warns)

JPEG with an embedded sRGB profile

Accepted, converted through ImageCms (the test used an sRGB profile; other RGB profiles go through the same call, and a CMYK profile needs a CMYK input mode instead)

Transparent PNG of 400 by 600

Accepted with two widths (320 and 400), but convert("RGB") drops the alpha channel and keeps the colour underneath, so flatten onto a background colour first when transparency matters

Image.MAX_IMAGE_PIXELS deserves the detail in that table: Pillow emits a DecompressionBombWarning above the limit and raises DecompressionBombError only above twice the limit, which is why the module checks the pixel count itself (and why -W error or a warnings filter is not a substitute for a limit). verify() reads headers and checksums without decoding the pixels, and leaves the image object unusable, so the module opens the bytes a second time. The sniffing of magic bytes before Image.open, see security and operations, is a cheap first filter for anything that Pillow could otherwise try to parse.

flowchart LR B["Bytes from storage"] --> V["Image.open and verify"] V --> G{"Format allowed, pixels under the cap?"} G -- "no" --> R["Rejected: failed, permanent"] G -- "yes" --> T["exif_transpose, ICC to sRGB, RGB"] T --> W["Per width: resize, save AVIF, WebP, JPEG"] T --> H["Resize to 64 x 96, BlurHash 3 x 4"] W --> J["Record: id, size, variants, blurhash"] H --> J

Pillow or pyvips

Both produce the same variants, the difference is memory and time on large inputs. The test input was a 6000 by 9000 pixel JPEG (3.2 MB on disk), reduced to a 640 by 960 JPEG at quality 80, each in a fresh process (peak resident memory from resource.getrusage):

Approach Time Peak memory

Pillow, exif_transpose, convert, resize (full decode)

664 ms

692 MB

Pillow, Image.thumbnail640, 960 (decodes at reduced scale)

282 ms

59 MB

pyvips, Image.thumbnail

186 ms

55 MB

The first row is what make_variants above does, and it is the one that grows with the pixel count: a decoded 54-megapixel RGB image is 162 MB, and exif_transpose and convert each make another full copy before the resize. So the claim that pyvips is lighter than Pillow holds against that code. Image.thumbnail (and Image.draft on JPEG, which asks libjpeg to decode at 1/2, 1/4 or 1/8 scale) closes most of the gap for JPEG inputs, at the price of giving up exif_transpose and ICC handling on the full-size image unless you apply them to the reduced one. A format without a reduced-scale decode keeps pyvips ahead: for a PNG with the same pixels (23 MB on disk), Pillow’s thumbnail needed 474 ms and 274 MB, and pyvips 396 ms and 97 MB, because libvips decodes the PNG as a stream. For the ladder of three widths, a pyvips thumbnail per width reads the source three times, with a shrink-on-load for JPEG each time, which is still cheaper than one full decode.

Production notes for the BlurHash packages

Two PyPI distributions exist and they are not compatible. blurhash-python (woltapp, 1.2.2) and blurhash (halcy, 1.1.5) both install a top-level module called blurhash, so installing both silently leaves whichever was written last, and the signatures differ: encode(image, x_components, y_components) takes a Pillow image or file in the first, and encode(image, components_x=4, components_y=4, linear=False) takes a NumPy array or a list of pixel rows in the second. The packages in the earlier example use the first. What else the test run showed:

  • blurhash.encode of the woltapp package closes the Pillow image it is given (a later im.load() raised ValueError: Operation on closed image), so encode from a throwaway thumbnail, as the code above does.

  • It wraps the C reference implementation. On the same 64 by 96 pixels it returned TKAxG?R,9Gm#f8WC0Lt6?GN1j[t6, while the TypeScript package (and blurhash-java) returned TIAxG?R,4pm#f8WB01t6?aN2j[t6. The difference is the quantisation of the largest AC value (absolute value in C, signed value in TypeScript). Both decode to nearly the same picture, with a mean difference of 4.6 on a 0 to 255 scale at 32 by 48 pixels.

  • decode(hash, width, height, punch=0.5) raises ValueError ("must be >= 1"): this decoder accepts only whole numbers from 1 up, which is the same practical limit as the punch | 1 of the TypeScript decoder described on the BlurHash page.

  • Encoding from the 2400 by 3600 original took 5.1 seconds in the Python wrapper (it builds a Python list of every pixel), from a 600 by 900 copy 300 ms, and from the 64 by 96 thumbnail 2 ms. Always downscale first.

How much a bigger grid helps, measured as the mean absolute error between the decoded 32 by 48 hash and a box-reduced copy of the cover (hard-edged lettering is the part that a few cosine components cannot represent):

Components Characters Mean error (0 to 255)

1 x 1

6

44.8

2 x 2

12

41.7

3 x 4

28

37.3

4 x 6

52

34.8

6 x 9

112

28.0

9 x 9

166

27.9

The error falls slowly and flattens after 6 by 9, while the string grows to 166 characters, which is why 3 by 4 for a portrait and 4 by 3 for a landscape are the defaults.

Video libraries

Library Status Notes

ffmpeg-python

Unmaintained since 2019 (0.2.0)

A builder for FFmpeg command lines. Still works for simple graphs, but it is not updated for newer FFmpeg options. Avoid it for new code.

MoviePy

Maintained (2.2.1)

Python editing library on top of FFmpeg. Suited to editing, overlays and clips, not to bulk transcoding, since it decodes frames in Python.

subprocess and FFmpeg

n/a

A direct call to the ffmpeg and ffprobe executables. The most predictable option and the one to prefer for transcoding.

subprocess

import json
import subprocess

QUIET = ["-nostdin", "-hide_banner", "-loglevel", "error"]    # no stdin reads, no banner, errors only

def run(args: list[str], timeout: int) -> subprocess.CompletedProcess:
    try:
        return subprocess.run(args, check=True, capture_output=True, text=True, timeout=timeout)
    except subprocess.CalledProcessError as exc:
        raise RuntimeError(f"{args[0]} failed with exit code {exc.returncode}: {exc.stderr.strip()[-500:]}") from exc

def probe(path: str) -> dict:
    out = run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_name,width,height",
               "-of", "json", path], timeout=30)
    return json.loads(out.stdout)

def transcode(src: str, dst: str, height: int = 720) -> None:
    run(["ffmpeg", *QUIET, "-y", "-i", src, "-vf", f"scale=-2:{height}",
         "-c:v", "libx264", "-preset", "slow", "-crf", "22", "-g", "48", "-keyint_min", "48",
         "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", dst], timeout=3600)

def cover(src: str, dst: str, seconds: float) -> None:
    run(["ffmpeg", *QUIET, "-y", "-ss", str(seconds), "-i", src, "-frames:v", "1", "-q:v", "2", dst], timeout=120)

Pass the arguments as a list, never as a shell string, so file names from users cannot inject options or commands, and always set a timeout (subprocess.run kills the child it started when the timeout expires and raises TimeoutExpired). -nostdin stops FFmpeg from reading the worker’s standard input, which can stall or consume bytes when the worker runs under a supervisor, and -loglevel error keeps the captured stderr short enough to put into the job’s failure reason. Reference: Python subprocess and the commands in video encoding fundamentals.

The functions were run against the 10 second, 1920 by 1080 H.264 and AAC test clip with FFmpeg 6.1.1. probe returned the streams h264 1920x1080 and aac and format.duration "10.000000" (the duration is a string in ffprobe’s JSON). transcode wrote a 1280 by 720 MP4 of 2,501,175 bytes in 1.9 seconds, and cover at 1.0 second a 112,818 byte JPEG in 0.18 seconds (an input seek, so FFmpeg jumps to the keyframe before that position instead of decoding from the start). A file that is not a video produced a RuntimeError that carries the decoder’s reason: ffmpeg failed with exit code 183: ... moov atom not found ... Invalid data found when processing input. That message, not a bare exit code, is what a failed job should store: the exit code is a truncated internal error number, not a documented interface.

MoviePy v2

MoviePy 2 renamed much of its API: moviepy.editor is gone (import from moviepy), resize became resized, subclip became subclipped, and the set_* methods became with_*.

from moviepy import VideoFileClip

with VideoFileClip("input.mov") as clip:
    small = clip.resized(height=360).subclipped(0, 10)       # first 10 seconds at 360p
    small.write_videofile("preview.mp4", codec="libx264", audio_codec="aac", fps=24)
    clip.save_frame("cover.jpg", t=clip.duration * 0.1)      # frame at 10 percent

Use it for previews and montage, and use FFmpeg directly for the renditions. The snippet above produced a 542,320 byte 360p preview and a 80,369 byte cover, and it works unchanged on MoviePy 2.2.1 (importing moviepy.editor raises ModuleNotFoundError). It took 20 seconds for the 10 second 1080p clip, while the equivalent FFmpeg command (-vf scale=-2:360 -r 24 -c:v libx264 -c:a aac) took 0.84 seconds, because MoviePy moves every decoded frame through Python and NumPy. ffmpeg-python 0.2.0 (released on 2019-07-06) still builds working command lines for simple graphs: ffmpeg.input(...).filter("scale", -2, 360).output(..., vcodec="libx264") ran and wrote a valid file. Reference: MoviePy documentation.

A FastAPI upload endpoint

The framework side is covered in forms and file uploads. For media, the endpoint should not receive the file at all when a pre-signed URL can be used, see upload pipelines. For small images, accepting the upload directly is fine. The endpoint below uses the process function of the cover job above, with dictionaries standing in for object storage and the media table:

from fastapi import BackgroundTasks, FastAPI, File, HTTPException, UploadFile
import uuid
from media_pipeline import Rejected, process

app = FastAPI()
MAX_BYTES = 10 * 1024 * 1024
ORIGINALS: dict[str, bytes] = {}      # stands in for the private uploads/ prefix
STATUS: dict[str, dict] = {}          # stands in for the media table

def process_image(media_id: str) -> None:
    try:
        STATUS[media_id] = {"status": "ready", **process(ORIGINALS[media_id])}
    except Rejected as exc:
        STATUS[media_id] = {"status": "failed", "reason": str(exc)}

@app.post("/images", status_code=202)
async def upload_image(background: BackgroundTasks, file: UploadFile = File(...)):
    data = await file.read(MAX_BYTES + 1)
    if len(data) > MAX_BYTES:
        raise HTTPException(status_code=413, detail="File too large")
    media_id = str(uuid.uuid4())
    ORIGINALS[media_id] = data
    STATUS[media_id] = {"status": "processing"}
    background.add_task(process_image, media_id)    # small, fast work only
    return {"id": media_id, "status": "processing"}

@app.get("/images/{media_id}")
def image_status(media_id: str):
    if media_id not in STATUS:
        raise HTTPException(status_code=404)
    return STATUS[media_id]

Exercised with FastAPI 0.162 and its TestClient: posting the phone JPEG returned 202 with {"id": "...", "status": "processing"}, and the status endpoint then returned ready, 2400 by 3600, the BlurHash TKAeBpR,9GiXf8WC0Lt6?GN1j[t6 and nine variants. A GIF returned failed with the reason not a decodable image, and a body of 10 MB plus five bytes returned 413 File too large. The test client runs background tasks before it returns, whereas a real server runs them after the response has been sent. Two details of the endpoint matter. First, file.read(MAX_BYTES + 1) protects memory but not disk or time: the multipart parser has already spooled the whole body to a temporary file before the handler runs, so also cap the request size in the reverse proxy and in the pre-signed URL. Second, process_image is a plain function, so Starlette runs it in a thread pool and the event loop keeps serving requests, but the pixels are still processed in the same process, which is the next problem.

sequenceDiagram participant C as Client participant A as FastAPI participant T as Thread pool participant Q as Real queue and worker C->>A: POST /images A-->>C: 202 with id, status processing A->>T: BackgroundTasks runs process_image Note over T: lost if the process restarts, no retry A->>Q: alternative: publish a job Q-->>A: status updates in the database C->>A: GET /images/id A-->>C: processing, then ready with variants

BackgroundTasks runs the function in the same process after the response is sent. That is fine for resizing a small image. It is not fine for video, for three reasons: a transcode can take minutes and would hold a worker slot, the work is lost if the process restarts or the pod is rescheduled, and there are no retries, backoff, dead-letter queue or visibility into progress. For video (and for any heavy image work), publish a job to a real queue (Celery, RQ, Dramatiq, or a cloud queue) and process it in a separate worker deployment. See settings, lifespan and background tasks for what BackgroundTasks does and does not do, and the queue patterns in upload pipelines.