Photos: JPEG (fast, universal) or WebP/AVIF (much smaller, slower to
encode). Graphics, screenshots and anything with transparency: PNG or lossless WebP. Animation: WebP or GIF.
16-bit or scientific data: PNG or TIFF. HEIC needs the pillow-heif plugin, and Pillow can write PDF but not read it.
How many formats Pillow handles
from PIL import Image, features
Image.init() # load every format plugin
readable, writable = set(Image.OPEN), set(Image.SAVE)
print(len(readable), "formats can be opened,", len(writable), "can be saved")
print("save-only:", sorted(writable - readable))
print("open-only (sample):", sorted(readable - writable)[:12], "...")
print("HEIF/HEIC readable without a plugin:", "HEIF" in readable)
print("codecs:", {name: features.check(name) for name in ["jpg", "zlib", "webp", "avif", "jpg_2000", "libtiff"]})
43 formats can be opened, 30 can be saved
save-only: ['MPO', 'PALM', 'PDF']
open-only (sample): ['CUR', 'DCX', 'FITS', 'FLI', 'FTEX', 'GBR', 'IMT', 'IPTC', 'MCIDAS', 'MPEG', 'PCD', 'PIXAR'] ...
HEIF/HEIC readable without a plugin: False
codecs: {'jpg': True, 'zlib': True, 'webp': True, 'avif': True, 'jpg_2000': True, 'libtiff': True}
Pillow reads far more formats than it writes. PDF is save-only (use pdf2image or PyMuPDF to read PDFs).
HEIC/HEIF is missing from both lists: it needs the pillow-heif plugin (see
converting formats).
Size, speed and decode time for a photo
import io
import time
from PIL import Image
Image.init() # register every format plugin (AVIF included)
photo = Image.open("photo.jpg").convert("RGB") # 1600 x 1067
photo.load()
settings = {
"JPEG q85": ("JPEG", {"quality": 85}),
"PNG": ("PNG", {}),
"WebP q80": ("WEBP", {"quality": 80}),
"AVIF q60": ("AVIF", {"quality": 60}),
"TIFF (none)": ("TIFF", {}),
"BMP": ("BMP", {}),
}
for name, (fmt, kw) in settings.items():
enc, dec = [], []
for _ in range(3):
buf = io.BytesIO()
t = time.perf_counter(); photo.save(buf, fmt, **kw); enc.append(time.perf_counter() - t)
buf.seek(0)
t = time.perf_counter(); Image.open(buf).load(); dec.append(time.perf_counter() - t)
print(f"{name:<12} {buf.getbuffer().nbytes / 1024:8.1f} KB encode {min(enc) * 1000:7.1f} ms decode {min(dec) * 1000:6.1f} ms")
JPEG q85 188.9 KB encode 4.1 ms decode 5.0 ms
PNG 1295.1 KB encode 288.4 ms decode 32.9 ms
WebP q80 78.3 KB encode 109.5 ms decode 21.9 ms
AVIF q60 61.9 KB encode 237.2 ms decode 9.4 ms
TIFF (none) 5002.2 KB encode 1.6 ms decode 1.9 ms
BMP 5001.6 KB encode 1.5 ms decode 1.9 ms
Encoding cost matters when you generate images on request; decoding cost matters for whoever opens them, thousands of times. Among compressed formats JPEG wins both; uncompressed TIFF and BMP are faster still, but only because they write raw pixels at 26× the size. WebP and AVIF are the right choice when bytes over the network matter more than CPU, and AVIF in particular decodes quickly for its size.
Transparency, animation and bit depth per format
import io
from PIL import Image
photo = Image.open("photo.jpg").resize((800, 534))
logo = Image.open("logo.png") # RGBA with transparent corners
frames = [photo, photo.transpose(Image.Transpose.FLIP_LEFT_RIGHT)]
def save(img, fmt, **kw):
buf = io.BytesIO()
img.save(buf, fmt, **kw)
buf.seek(0)
return buf
def check(fn):
try:
return fn()
except Exception:
return "-"
print(f"{'format':<9}{'photo KB':>9} {'keeps alpha':<12}{'animation':<10}{'16-bit grey'}")
grey16 = photo.convert("I").point(lambda v: v * 257).convert("I;16")
for fmt in ["JPEG", "PNG", "WEBP", "AVIF", "GIF", "TIFF", "BMP", "JPEG2000", "TGA", "PPM"]:
kb = check(lambda: f"{save(photo, fmt).getbuffer().nbytes / 1024:.0f}")
alpha = check(lambda: "yes" if Image.open(save(logo, fmt)).convert("RGBA").getpixel((2, 2))[3] == 0 else "no")
anim = check(lambda: "yes" if getattr(Image.open(save(frames[0], fmt, save_all=True, append_images=frames[1:])),
"n_frames", 1) > 1 else "no")
deep = check(lambda: "yes" if Image.open(save(grey16, fmt)).mode in ("I;16", "I", "I;16B") else "no")
print(f"{fmt:<9}{kb:>9} {alpha:<12}{anim:<10}{deep}")
format photo KB keeps alpha animation 16-bit grey
JPEG 39 - - -
PNG 426 yes yes yes
WEBP 28 yes yes no
AVIF 34 yes yes no
GIF 152 yes yes no
TIFF 1252 yes yes yes
BMP 1252 no - -
JPEG2000 411 yes - yes
TGA 1252 yes - -
PPM 1252 no - yes
"-" means saving raised an error; "no" means the file saved but the feature was lost when it was opened again. Sizes use each format's defaults on an 800×534 copy, so they compare defaults rather than tuned settings. GIF keeps transparency as one palette entry, so soft edges become hard, and it has at most 256 colours per frame. PNG's "yes" for animation is APNG, which browsers play but many viewers show as a still. BMP writes the alpha byte with a header that does not declare it, so readers (Pillow included) open it as RGB.
Format names, extensions and KeyError: 'JPG'
Pillow picks the format from the file extension, or from the format argument when you pass one. The two
go through different tables, which is why "photo.JPG" works but format="JPG" does not:
import io
from PIL import Image
Image.init()
ext = Image.registered_extensions() # {".jpg": "JPEG", ".jfif": "JPEG", ...}
print(len(ext), "extensions;", ".jpg ->", ext[".jpg"], " .tif ->", ext[".tif"], " .ico ->", ext[".ico"])
img = Image.new("RGB", (64, 64), "teal")
img.save("a.JPG") # the extension decides, in any case
img.save("a.png", "jpeg") # an explicit format wins, in any case (a JPEG named .png)
print("a.png is really:", Image.open("a.png").format)
for label, args in [("'b.jpg', 'JPG'", ("b.jpg", "JPG")), ("'b.heic'", ("b.heic",)), ("'b.svg'", ("b.svg",)),
("'no_extension'", ("no_extension",)), ("io.BytesIO()", (io.BytesIO(),))]:
try:
img.save(*args)
except (KeyError, ValueError) as e:
print(f"save({label})".ljust(23), "->", f"{type(e).__name__}: {e}")
buf = io.BytesIO()
img.save(buf, format="PNG") # in-memory files have no name: pass format=
print("BytesIO with format='PNG':", buf.getbuffer().nbytes, "bytes")
70 extensions; .jpg -> JPEG .tif -> TIFF .ico -> ICO
a.png is really: JPEG
save('b.jpg', 'JPG') -> KeyError: 'JPG'
save('b.heic') -> ValueError: unknown file extension: .heic
save('b.svg') -> ValueError: unknown file extension: .svg
save('no_extension') -> ValueError: unknown file extension:
save(io.BytesIO()) -> ValueError: unknown file extension:
BytesIO with format='PNG': 153 bytes
KeyError: 'JPG': the format name is"JPEG". Extensions are mapped (.jpg,.jpeg,.jpe,.jfifall mean JPEG), format names are not. Case does not matter in either.ValueError: unknown file extension: either the name has no extension, the target is an in-memory buffer (passformat=), or Pillow cannot write that format at all. HEIC needspillow-heif; SVG is not a raster format and Pillow neither reads nor writes it.- An explicit format always wins, so
save("a.png", "jpeg")quietly writes a JPEG with a .png name. When the format comes from user input, derive the extension from it instead of trusting both.
What a plain save() keeps, and what it drops
import io
from PIL import Image
def reopen(img, fmt, **kw):
buf = io.BytesIO()
img.save(buf, fmt, **kw)
buf.seek(0)
return Image.open(buf)
photo = Image.open("photo.jpg") # has an ICC colour profile
phone = Image.open("phone.jpg") # has EXIF (Orientation)
for fmt in ["JPEG", "PNG", "WEBP"]:
print(f"{fmt:<5} plain save keeps ICC: {'icc_profile' in reopen(photo, fmt).info!s:<5} "
f"EXIF: {len(reopen(phone, fmt).getexif()) > 0}")
kept = reopen(photo, "JPEG", icc_profile=photo.info["icc_profile"])
print("JPEG with icc_profile= keeps ICC:", "icc_profile" in kept.info)
print("JPEG with exif= keeps EXIF:", len(reopen(phone, "JPEG", exif=phone.getexif()).getexif()) > 0)
JPEG plain save keeps ICC: False EXIF: False
PNG plain save keeps ICC: True EXIF: False
WEBP plain save keeps ICC: False EXIF: False
JPEG with icc_profile= keeps ICC: True
JPEG with exif= keeps EXIF: True
Re-saving a JPEG or WebP drops its colour profile and EXIF unless you pass them back. Losing the ICC profile shifts colours on
wide-gamut photos (see ImageCms); losing EXIF loses the camera data and the Orientation tag, so
apply ImageOps.exif_transpose() first if you drop it. PNG keeps the profile on its own. Details and editing are in
reading and writing EXIF.
The save options that matter, per format
import io
from PIL import Image
photo = Image.open("photo.jpg") # 1600 x 1067 photo
logo = Image.open("logo.png") # small RGBA graphic
cases = [
("JPEG", photo, {"quality": 85}),
("JPEG", photo, {"quality": 85, "optimize": True}),
("JPEG", photo, {"quality": 85, "progressive": True}),
("JPEG", photo, {"quality": 85, "subsampling": 0}),
("JPEG", photo, {"quality": "keep"}),
("PNG", logo, {}),
("PNG", logo, {"optimize": True}),
("PNG", logo, {"compress_level": 1}),
("WEBP", photo, {"quality": 80}),
("WEBP", photo, {"quality": 80, "method": 6}),
("WEBP", logo, {"lossless": True}),
("AVIF", photo, {"quality": 60}),
("AVIF", photo, {"quality": 60, "speed": 2}),
("TIFF", photo, {"compression": "tiff_lzw"}),
("TIFF", photo, {"compression": "tiff_adobe_deflate"}),
("TIFF", photo, {"compression": "jpeg", "quality": 85}),
("GIF", logo, {"optimize": True}),
]
for fmt, img, kw in cases:
buf = io.BytesIO()
img.save(buf, fmt, **kw)
args = ", ".join(f"{k}={v!r}" for k, v in kw.items()) or "(defaults)"
print(f"{fmt:<5} {'photo' if img is photo else 'logo':<6}{args:<38}{buf.getbuffer().nbytes / 1024:8.1f} KB")
JPEG photo quality=85 188.9 KB
JPEG photo quality=85, optimize=True 183.8 KB
JPEG photo quality=85, progressive=True 175.4 KB
JPEG photo quality=85, subsampling=0 234.0 KB
JPEG photo quality='keep' 233.0 KB
PNG logo (defaults) 3.8 KB
PNG logo optimize=True 3.1 KB
PNG logo compress_level=1 7.8 KB
WEBP photo quality=80 78.3 KB
WEBP photo quality=80, method=6 75.3 KB
WEBP logo lossless=True 1.1 KB
AVIF photo quality=60 61.9 KB
AVIF photo quality=60, speed=2 56.3 KB
TIFF photo compression='tiff_lzw' 3128.6 KB
TIFF photo compression='tiff_adobe_deflate' 1887.4 KB
TIFF photo compression='jpeg', quality=85 487.3 KB
GIF logo optimize=True 3.1 KB
| Format | Option | What it does |
|---|---|---|
| JPEG | quality | 1–95 (default 75). "keep" reuses the source file's quantisation tables, so a re-save keeps the original's quality (this photo was saved at 92, hence the larger file). Only for images opened from a JPEG. |
optimize | Computes optimal Huffman tables: a few percent smaller, identical pixels. | |
progressive | Loads coarse-to-fine in browsers; often slightly smaller too. | |
subsampling | 0 = 4:4:4 (sharp colour edges, larger), 2 = 4:2:0 (the default, at every quality). | |
icc_profile, exif, dpi | Metadata to write; nothing is copied from the source unless you pass it. | |
| PNG | optimize | Tries harder to compress; always lossless. |
compress_level | 0–9 (default 6). Lower is faster and larger. optimize=True overrides it with 9. | |
| WebP | quality | 0–100 (default 80). |
method | 0–6 effort (default 4): 6 is slower and a little smaller. | |
lossless | Exact pixels, usually far smaller than PNG for graphics. | |
| AVIF | quality | 0–100 (default 75). |
speed | 0–10 (default 6): lower is slower and smaller. | |
| TIFF | compression | "tiff_lzw", "tiff_adobe_deflate" (lossless) or "jpeg" (lossy); default none. |
| GIF | optimize | Drops unused palette entries. |
Measured trade-offs for each knob, with charts, are in reducing file size.
ICO favicons
from PIL import Image, ImageOps
logo = Image.open("logo.png").convert("RGBA") # 600 x 360, not square
logo.save("wide.ico")
print("non-square logo:", sorted(Image.open("wide.ico").info["sizes"])[:3], "...")
square = ImageOps.pad(logo, (256, 256)) # centre it on a transparent 256 x 256 square
square.save("favicon.ico") # default: every standard size up to 256 that fits
print("default sizes: ", sorted(Image.open("favicon.ico").info["sizes"]))
square.save("small.ico", sizes=[(16, 16), (32, 32), (48, 48)])
ico = Image.open("small.ico")
print("chosen sizes: ", sorted(ico.info["sizes"]), "opens at", ico.size)
ico.size = (16, 16) # pick which embedded size to load
ico.load()
print("after size = (16, 16):", ico.size)
tiny = square.resize((12, 12))
tiny.save("tiny.ico") # smaller than 16: its own size is used (Pillow 13)
print("12x12 saved as:", sorted(Image.open("tiny.ico").info["sizes"]))
try:
tiny.save("bad.ico", sizes=[(32, 32)]) # nothing in sizes fits inside the image
except ValueError as e:
print("ValueError:", e)
non-square logo: [(16, 10), (24, 14), (32, 19)] ...
default sizes: [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
chosen sizes: [(16, 16), (32, 32), (48, 48)] opens at (48, 48)
after size = (16, 16): (16, 16)
12x12 saved as: [(12, 12)]
ValueError: All sizes too large for image
One .ico file holds several sizes. Without sizes, Pillow writes every standard size from 16 to 256 that is not
larger than the image, and it keeps the aspect ratio: a wide logo becomes 16×10 icons, which browsers stretch. Pad it to a
square of at least 256×256 with ImageOps.pad() first. Pillow 13 changed two edge cases: an image smaller than
16×16 is now saved at its own size (older versions wrote an ICO with no images in it), and a sizes list where nothing
fits raises ValueError. When opening, the largest size loads; set ico.size before load() to pick another.
JPEG XL: through a plugin
Pillow 13.0.0 has no JPEG XL support of its own (saving as "JXL" raises KeyError). The
pillow-jxl-plugin package adds it; importing pillow_jxl registers the format:
import io
import os
import warnings
import numpy as np
from PIL import Image
Image.init()
print("JPEG XL built into Pillow:", "JXL" in Image.SAVE)
import pillow_jxl # pip install pillow-jxl-plugin: registers the JXL format
warnings.simplefilter("ignore") # the plugin warns when it picks lossless JPEG transcoding
photo = Image.open("photo.jpg")
print(f"original JPEG file: {os.path.getsize('photo.jpg') / 1024:6.1f} KB")
buf = io.BytesIO()
photo.save(buf, "JXL") # from a JPEG: lossless recompression of the JPEG data
print(f"JXL, default from a JPEG (lossless): {buf.tell() / 1024:6.1f} KB")
buf.seek(0)
same = np.array_equal(np.asarray(Image.open(buf).convert("RGB")), np.asarray(photo.convert("RGB")))
print(" pixels identical to the JPEG:", same)
for q in (70, 80, 90):
out = io.BytesIO()
photo.save(out, "JXL", quality=q, lossless_jpeg=False) # re-encode the pixels instead
print(f"JXL, re-encoded at quality={q}: {out.tell() / 1024:6.1f} KB")
JPEG XL built into Pillow: False
original JPEG file: 233.4 KB
JXL, default from a JPEG (lossless): 187.2 KB
pixels identical to the JPEG: True
JXL, re-encoded at quality=70: 66.5 KB
JXL, re-encoded at quality=80: 86.7 KB
JXL, re-encoded at quality=90: 135.0 KB
JPEG XL has a trick no other format here has: an existing JPEG can be recompressed losslessly, about a fifth smaller with
exactly the same pixels. The plugin does this by default when the image came from a
JPEG, which is why quality seems to be ignored; pass lossless_jpeg=False to encode the pixels at the
quality you ask for. Check that the browsers and tools you target can display JPEG XL before publishing it.
Reading PDF and SVG files
Pillow writes PDF but cannot open it, and it has no SVG support at all: both raise UnidentifiedImageError.
PyMuPDF renders both into pixels that Pillow can take over, with
nothing else to install (pdf2image also works for PDF, but needs the Poppler programs on the system):
import pymupdf # pip install pymupdf
from PIL import Image, UnidentifiedImageError
photo = Image.open("photo.jpg")
photo.save("doc.pdf", save_all=True, append_images=[photo.rotate(180)], resolution=150)
open("icon.svg", "w").write('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="80">'
'<circle cx="40" cy="40" r="30" fill="#e44"/>'
'<rect x="70" y="20" width="40" height="40" fill="#36c" opacity="0.5"/></svg>')
for name in ["doc.pdf", "icon.svg"]:
try:
Image.open(name)
except UnidentifiedImageError as e:
print("Pillow:", e)
# PDF pages -> Pillow images, rendered at 150 dpi
for number, page in enumerate(pymupdf.open("doc.pdf"), 1):
pix = page.get_pixmap(dpi=150)
img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
img.save(f"page_{number}.png")
print(f"page {number}: {img.size} {img.mode}")
# SVG -> transparent Pillow image, rendered at 4x. With alpha, PyMuPDF's samples are premultiplied: mode "RGBa".
pix = pymupdf.open("icon.svg")[0].get_pixmap(alpha=True, matrix=pymupdf.Matrix(4, 4))
svg = Image.frombytes("RGBa", (pix.width, pix.height), pix.samples).convert("RGBA")
print("svg:", svg.size, svg.mode, "| corner", svg.getpixel((0, 0)), "| half-transparent blue", svg.getpixel((360, 160)))
wrong = Image.frombytes("RGBA", (pix.width, pix.height), pix.samples)
print("read as plain RGBA instead:", wrong.getpixel((360, 160)), "(too dark)")
Pillow: cannot identify image file 'doc.pdf'
Pillow: cannot identify image file 'icon.svg'
page 1: (1600, 1067) RGB
page 2: (1600, 1067) RGB
svg: (480, 320) RGBA | corner (0, 0, 0, 0) | half-transparent blue (50, 101, 204, 126)
read as plain RGBA instead: (25, 50, 101, 126) (too dark)
Two details decide the result. dpi= (or a Matrix zoom) sets the pixel size, since PDF and SVG are
measured in points, not pixels. And with alpha=True PyMuPDF returns premultiplied colour, so read it as
"RGBa" and convert; reading it as "RGBA" darkens every semi-transparent edge, as the last line shows. PyMuPDF
is licensed under the AGPL (or commercially); for SVG alone, cairosvg is an MIT-licensed alternative.
Which format for which job
| Job | Format | Settings to start with |
|---|---|---|
| Photos on a website | WebP or AVIF, JPEG fallback | quality=80 (WebP), quality=60 (AVIF), quality=85, optimize=True (JPEG) |
| Logos, icons, screenshots | PNG or lossless WebP | optimize=True; quantize(colors) for few-colour graphics |
| Transparent images | PNG, WebP, AVIF | Never JPEG: it has no alpha (cannot write mode RGBA as JPEG) |
| Animation | WebP (smaller) or GIF (universal) | save_all=True, append_images=[...], duration=, loop=0 (animated GIFs) |
| Print, scans, 16-bit | TIFF or PNG | compression="tiff_lzw" (TIFF guide) |
| Documents | PDF (write only) | save_all=True, resolution= (images to PDF) |
Sources
What this page shows comes from running its code with Pillow 13.0.0. The API details and version history were checked against these primary sources:
Related
The outputs and images on this page are the real results of running every example with Pillow 13.0.0 on Python 3.13 (Linux) on 2026-10-29. Every example is also re-run automatically on macOS (Darwin 25.6.0, Pillow 12.3.0), Linux (Linux 6.17.0-1022-azure, Pillow 12.3.0), Windows (Windows 2025Server, Pillow 12.3.0); the line under each example shows the result per operating system. The DejaVu Sans font files sit next to each script so font examples behave the same everywhere. Sample photos: NASA/Sam Lott, public domain. Spotted something wrong? Tell us.