How-to guides
- GuideResize an image and keep the aspect ratio with Pillow
Resize without distortion: thumbnail(), contain, cover, fit and pad compared with real output, plus sideways phone photos, batch resizing and speed, measured.
- GuideAdd text to an image with Pillow
Draw text with Pillow: load fonts, centre with anchors, wrap and fit text, outlines, drop shadows, bold and italic, emoji and non-Latin scripts. Real output.
- GuideConvert images between PNG, JPEG, WebP, AVIF and more with Pillow
Convert between PNG, JPEG, WebP, AVIF, HEIC, GIF, ICO and PDF with Pillow: measured sizes, keeping transparency and EXIF, animations and a batch converter.
- GuideConvert between PIL images, NumPy arrays and PyTorch tensors
PIL Image to NumPy array or PyTorch tensor and back: shapes and dtypes per mode, read-only arrays, channels-first tensors, black images. Tested.
- GuideGet an image's size, format, mode and file size with Pillow
Read width, height, format, mode, DPI, file size and metadata with Pillow without decoding pixels, plus the EXIF-rotated size gotcha and a fast folder scanner.
- GuideOpen an image from a URL, bytes or a base64 string
Load images into Pillow from a URL, bytes, base64, a data URI or an upload, without temporary files: errors, size limits and streams handled. Tested examples.
- GuideConvert a PIL image to bytes, base64 or a data URI
Turn a Pillow image into PNG or JPEG bytes, base64 or a data URI and return it from Flask, FastAPI or Django without a file. Why tobytes() is not what you want.
- GuideReduce image file size with Pillow, measured
Shrink JPEG, PNG and WebP with Pillow: quality, optimize, progressive, subsampling, palette PNGs, stripping metadata and resizing, each measured on one photo.
- GuideDisplay a PIL image: show(), Jupyter, matplotlib and Tkinter
Show a PIL image: why img.show() sometimes does nothing, inline in Jupyter and Colab, with matplotlib (and its float error), figures to images, and Tkinter.
- GuideConvert between Pillow and OpenCV without swapping colours
Convert PIL images to OpenCV arrays and back without the blue-skin bug: BGR vs RGB, alpha, greyscale, imread vs Image.open, and speed. Tested, real output.
- GuideRead EXIF data with Pillow: date taken, camera, GPS and more
Read EXIF with getexif(): date taken, camera, GPS in decimal degrees, orientation, XMP, PNG text and DPI, plus editing and stripping metadata. Tested output.
- GuideCombine images side by side, stacked or in a grid
Merge images with Pillow: side by side, stacked or in a grid, with different sizes, gaps and labels, plus blending, fading and averaging. Tested, real output.
- GuideCrop an image with Pillow
How crop() boxes work (left, upper, right, lower), centre and aspect-ratio crops, circular avatars, and auto-cropping borders despite JPEG noise. Real output.
- GuideGet and change pixel values
Read and change pixel colours with getpixel, load(), get_flattened_data (getdata is deprecated) and NumPy, with the speed of each measured on a real photo.
- GuideOverlay a transparent PNG onto another image
Paste a transparent PNG (logo, watermark, sticker) onto a photo without black corners: paste with a mask vs alpha_composite, opacity, position, mask errors.
- GuideMake a white background transparent
Make white or any colour transparent with Pillow: why exact matching fails on JPEGs, tolerance and soft edges, and flood fill to keep white in the subject.
- GuideSplit an image into tiles
Cut an image into an N x M grid, fixed-size tiles, overlapping patches for machine learning or a carousel, with sizes that do not divide evenly. Real output.
- GuideInstall Pillow (the maintained PIL) the right way
Install Pillow with pip in a venv, conda, Jupyter or Docker; fix externally-managed-environment, Failed building wheel and pip install PIL. Tested commands.
- GuideConvert an image to greyscale or black and white
Greyscale with convert("L"), pure black and white with convert("1"), why it looks speckled, fixed and automatic Otsu thresholds, and keeping transparency.
- GuideImage modes explained
What each Pillow mode stores, its channels and getpixel values, which mode each format opens as, P vs L, and the conversions that silently lose data. Tested.
- GuideLoad and process every image in a folder
Load every image in a folder, resize or convert them all, sort names naturally, skip bad files, avoid Too many open files and use every CPU core. Tested.
- GuideCreate, read and resize animated GIFs
Make an animated GIF or WebP from frames, read frame counts and durations, extract frames, resize without losing the animation, and fix trails. Real output.
- GuideSave images as a PDF
Save one or many images as a PDF: why pages come out huge, setting the page size, fitting images on A4 with margins, file size, transparency, and PDF to images.
- GuideDraw rectangles, circles and lines on an image
Draw shapes with ImageDraw: box coordinates and outline width, translucent fills (and why alpha is ignored on RGB), smooth circles, thick lines, labelled boxes.
- GuideRotate or flip an image
rotate() turns counter-clockwise and crops by default. Rotate clockwise, keep the corners with expand=True, fill them, smooth edges, flip, fix phone photos.
- GuideRead and write TIFF files
Open multi-page TIFFs, save stacks, choose compression, keep 16-bit and float data through NumPy, read regions of huge files, and the 48-bit trap. Tested.
- GuideInvert image colours
Make a negative with ImageOps.invert and fix "not supported for mode RGBA": invert transparent PNGs keeping alpha, palette, CMYK and 16-bit images. Tested.
- GuideResampling filters compared: which one to use, measured
All eight Pillow 13 filters, NEAREST to LANCZOS plus the new MKS2013 and MKS2021, measured: aliasing, sharpness, speed, reducing_gap, and which to use when.
- GuideAffine and perspective transforms with Image.transform()
Why transform() coefficients seem backwards, a helper for normal matrices, shear, skew, perspective from four points and straightening a photographed page.
- GuideCount, find and replace colours in an image
Why getcolors() returns None, the dominant colours of a photo, replacing a colour exactly or with a tolerance, recolouring icons, hue shifts. Five ways timed.
- GuideImage uploads with Pillow in Django, Flask and FastAPI
A tested upload pipeline: reject fake and oversized images and decompression bombs, rotate phone photos, strip GPS, resize to WebP. Django, Flask, FastAPI, S3.
- GuideWhat is Pillow? PIL, Pillow and every version since 9.0
What Pillow is and how it relates to PIL, the latest version, what each major release changed, the release schedule, security fixes and the licence.
- GuidePillow vs OpenCV, scikit-image, pyvips and ImageMagick: which Python image library?
Pillow, OpenCV, scikit-image, pyvips or ImageMagick? All five compared on the same 15-megapixel photo for speed, install size and features.
Error fixes
Each one reproduces the error on a real Pillow install, explains the cause and shows the fix.
- ModuleNotFoundErrorModuleNotFoundError: No module named 'PIL'
Fix "No module named 'PIL'": install Pillow into the interpreter that runs your code. Tested commands for venv, Windows, macOS, Linux, conda, Jupyter, Docker.
- AttributeErrorAttributeError: module 'PIL.Image' has no attribute 'ANTIALIAS'
Image.ANTIALIAS was removed in Pillow 10. Use Image.LANCZOS (the same filter on every version), patch old libraries, and see why pinning Pillow<10 fails.
- AttributeErrorAttributeError: 'ImageDraw' object has no attribute 'textsize'
textsize() and getsize() were removed in Pillow 10. Replace them with textbbox() or textlength(): a drop-in helper, the centring fix and real measurements.
- UnidentifiedImageErrorPIL.UnidentifiedImageError: cannot identify image file
Why Pillow says "cannot identify image file": HTML saved as .jpg, empty downloads, unrewound BytesIO, HEIC, SVG. Each reproduced, with a diagnostic script.
- OSErrorOSError: cannot open resource (ImageFont.truetype)
ImageFont.truetype() raises "cannot open resource" when it cannot find the font. Where Pillow looks on Windows, macOS and Linux, and a loader with fallback.
- TypeErrorTypeError: Cannot handle this data type: (1, 1, 3), <f4
fromarray raises "Cannot handle this data type: (1, 1, 3), <f4" when no Pillow mode fits the dtype or shape. How to read it, and the fix for each array type.
- OSErrorOSError: cannot write mode F as JPEG (and P, LA, I;16, CMYK…)
"cannot write mode X as JPEG" means the format cannot store that mode. A tested table of modes per format, and the right conversion for RGBA, P, F, I;16, CMYK.
- OSErrorOSError: image file is truncated (N bytes not processed)
"image file is truncated" means the file ends early. Why open() works but load() fails, how to find bad files, and when LOAD_TRUNCATED_IMAGES is safe.
- DecompressionBombWarningDecompressionBombWarning: Image size exceeds limit, could be decompression bomb DOS attack
Pillow warns above 89,478,485 pixels and raises DecompressionBombError above twice that. What it protects, raising it safely, and handling huge images.
- TypeErrorTypeError: Image data of dtype object cannot be converted to float
matplotlib imshow() raises "Image data of dtype object cannot be converted to float" when given None, a path or a list instead of image data. Causes and fixes.
- TypeErrorTypeError: 'tuple' object does not support item assignment
Why changing a Pillow pixel's channel or img.size raises "'tuple' object does not support item assignment", the fixes, and the NumPy read-only array version.
- AttributeErrorscipy.misc has no attribute imread (or imresize, imsave, toimage)
scipy.misc.imread, imresize, imsave and toimage were removed. Drop-in replacements with Pillow and imageio, and the differences that silently change results.
- AttributeError / ImportErrormodule 'PIL' has no attribute 'Image', and other import mix-ups
Fix "module 'PIL' has no attribute 'Image'", "No module named 'Image'" and "cannot import name 'ImageTk'": each error reproduced, with the fix.
- ImportErrorImportError: cannot import name '_imaging' from 'PIL'
Pillow's compiled core failed to load: '_imaging', DLL load failed, built for another Pillow, missing libraries in Lambda or Docker, decoder jpeg not available.
- AttributeErrorAttributeError: module 'PIL.Image' has no attribute 'Resampling'
Image.Resampling and the other enums arrived in Pillow 9.1. Reproduced on 9.0.1, with the upgrade, a constant that works everywhere, and what pins old Pillow.
- Django fields.E210Cannot use ImageField because Pillow is not installed
Django's fields.E210, reproduced: Pillow missing, installed in another environment, or installed but broken (Django hides the real error). Tested on Django 6.
Nothing matches. Press / to search the whole site, including the reference and tools.
How these guides are made
Every code example is executed against Pillow 13.0.0 on Python 3.13 before publishing, and the printed output and images on each page come from that run. Version history is checked against Pillow's official release notes. Read more about our editorial process.