Read the upload as bytes and pass them to one function: Image.open(io.BytesIO(data), formats=[...]), check
width * height, call load() inside try, then ImageOps.exif_transpose(),
thumbnail() and save without exif= so the GPS location is gone. Never trust the file name or the
browser's content type. In Django, do not use form.cleaned_data["photo"].image for processing: it has been
verify()ed and cannot be used; open the file again.
One function for every framework
Keep the image handling out of the view, so the same tested code serves every framework and can be unit-tested without one:
import io
from PIL import Image, ImageOps, UnidentifiedImageError
MAX_BYTES = 15 * 1024 * 1024 # refuse bigger uploads before decoding anything
MAX_PIXELS = 40_000_000 # about 7700 x 5200; Pillow's own limit is 89 million
ALLOWED = ["JPEG", "PNG", "WEBP", "GIF", "AVIF"]
class BadImage(ValueError):
"""The upload is not an image we accept; the message is safe to show to the user."""
def process_upload(data: bytes, max_side=2048):
"""Validate an uploaded image and return (webp_bytes, info). Raises BadImage."""
if len(data) > MAX_BYTES:
raise BadImage(f"file is larger than {MAX_BYTES // 2**20} MB")
try:
img = Image.open(io.BytesIO(data), formats=ALLOWED) # reads only the header
except UnidentifiedImageError:
raise BadImage("not a supported image (JPEG, PNG, WebP, GIF or AVIF)")
except Image.DecompressionBombError: # Pillow refuses over 179 million pixels by itself
raise BadImage("image is too large")
if img.width * img.height > MAX_PIXELS: # checked before the pixels are decoded
raise BadImage(f"image is too large ({img.width} x {img.height} pixels)")
try:
img.load() # decode now: truncated or corrupt files fail here
except (OSError, SyntaxError) as e:
raise BadImage(f"image file is damaged ({e})")
original = (img.format, img.size)
img = ImageOps.exif_transpose(img) # phone photos: apply the rotation
img.thumbnail((max_side, max_side), Image.LANCZOS)
keep_alpha = img.has_transparency_data
img = img.convert("RGBA" if keep_alpha else "RGB")
out = io.BytesIO()
img.save(out, "WEBP", quality=82) # no exif= passed: GPS and camera data are dropped
return out.getvalue(), {"format": original[0], "original_size": original[1], "size": img.size,
"bytes": out.tell(), "transparent": keep_alpha}
The order matters. The byte limit runs before anything is decoded; Image.open() reads only the header, so the
pixel limit can refuse a 400-megapixel image before it allocates the memory; formats= stops Pillow from trying its
40 other plugins on hostile input; and load() is where truncated and corrupt files actually fail.
Tested against hostile files
import os
from PIL import ExifTags, Image
from uploads import BadImage, process_upload
for name in ["photo.jpg", "logo.png", "phone_gps.jpg", "fake.jpg", "truncated.jpg", "big.png", "bomb.png", "drawing.svg"]:
data = open(name, "rb").read()
try:
webp, info = process_upload(data)
except BadImage as e:
print(f"{name:<14}{len(data) / 1024:7.0f} KB rejected: {e}")
continue
open("out.webp", "wb").write(webp)
gps = Image.open("out.webp").getexif().get_ifd(ExifTags.IFD.GPSInfo)
print(f"{name:<14}{len(data) / 1024:7.0f} KB ok: {info['original_size']} -> {info['size']}, "
f"{info['bytes'] / 1024:.0f} KB WebP, GPS left: {bool(gps)}")
photo.jpg 233 KB ok: (1600, 1067) -> (1600, 1067), 85 KB WebP, GPS left: False
logo.png 4 KB ok: (600, 360) -> (600, 360), 5 KB WebP, GPS left: False
phone_gps.jpg 89 KB ok: (1200, 800) -> (800, 1200), 69 KB WebP, GPS left: False
fake.jpg 0 KB rejected: not a supported image (JPEG, PNG, WebP, GIF or AVIF)
truncated.jpg 117 KB rejected: image file is damaged (image file is truncated (39 bytes not processed))
big.png 12 KB rejected: image is too large (10000 x 10000 pixels)
bomb.png 47 KB rejected: image is too large
drawing.svg 0 KB rejected: not a supported image (JPEG, PNG, WebP, GIF or AVIF)
/home/you/.venv/lib/python3.13/site-packages/PIL/Image.py:3593: DecompressionBombWarning: Image size (100000000 pixels) exceeds limit of 89478485 pixels, could be decompression bomb DOS attack.
warnings.warn(
- fake.jpg is an HTML error page with an image name, the most common “image” that is not one. The extension and the browser's content type say JPEG; only opening it tells the truth.
- truncated.jpg opens fine (the header is intact) and fails in
load(). Without that call the error would surface later, in the middle of your resize, as an unhandled 500. Do not setImageFile.LOAD_TRUNCATED_IMAGES = Truefor uploads: it turns a broken upload into a grey half-image. - bomb.png is 48 KB on disk and 400 million pixels when decoded: 50 MB as 1-bit, 1.2 GB once converted to
RGB. Pillow itself raises
DecompressionBombErrorinImage.open()above 179 million pixels, from the header alone, so catch it there. Between 89 and 179 million pixels Pillow only warns, which is whyMAX_PIXELSsets a lower limit that fits your server (see DecompressionBombError). - phone_gps.jpg carries a GPS position, like most phone photos. Saving without
exif=removes it, andexif_transpose()has already applied the rotation the Orientation tag asked for, so nothing is lost. - drawing.svg is rejected because Pillow cannot read SVG at all; if you need SVG uploads, rasterise them deliberately (see reading PDF and SVG) and treat them as untrusted XML.
Flask
from flask import Flask, jsonify, request
from uploads import BadImage, process_upload
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 # Flask answers 413 above this, before your code runs
STORE = {} # stands in for your storage
@app.post("/photos")
def upload_photo():
file = request.files.get("photo")
if file is None or file.filename == "":
return jsonify(error="no file in field 'photo'"), 400
try:
webp, info = process_upload(file.read())
except BadImage as e:
return jsonify(error=str(e)), 400
key = f"photo-{len(STORE) + 1}.webp"
STORE[key] = webp
return jsonify(key=key, **info), 201
# The same requests a browser form (enctype="multipart/form-data") would send:
client = app.test_client()
for name in ["phone_gps.jpg", "fake.jpg", "bomb.png"]:
with open(name, "rb") as fh:
r = client.post("/photos", data={"photo": (fh, name)}, content_type="multipart/form-data")
print(name, r.status_code, r.get_json())
print("empty form", client.post("/photos", data={}).status_code)
phone_gps.jpg 201 {'bytes': 70978, 'format': 'JPEG', 'key': 'photo-1.webp', 'original_size': [1200, 800], 'size': [800, 1200], 'transparent': False}
fake.jpg 400 {'error': 'not a supported image (JPEG, PNG, WebP, GIF or AVIF)'}
bomb.png 400 {'error': 'image is too large'}
empty form 400
request.files["photo"] is a FileStorage; read() gives the bytes. Set
MAX_CONTENT_LENGTH so Flask itself refuses oversized requests with 413 before they reach your code, and keep the
byte limit in process_upload anyway for other callers.
FastAPI
from fastapi import FastAPI, HTTPException, UploadFile
from fastapi.testclient import TestClient
from uploads import MAX_BYTES, BadImage, process_upload
app = FastAPI()
@app.post("/photos", status_code=201)
async def upload_photo(photo: UploadFile): # needs: pip install python-multipart
data = await photo.read(MAX_BYTES + 1) # never read more than we would accept
try:
webp, info = process_upload(data)
except BadImage as e:
raise HTTPException(status_code=400, detail=str(e))
return {"filename": photo.filename, "content_type_claimed": photo.content_type, **info}
client = TestClient(app)
for name, claimed in [("photo.jpg", "image/jpeg"), ("fake.jpg", "image/jpeg"), ("truncated.jpg", "image/jpeg")]:
with open(name, "rb") as fh:
r = client.post("/photos", files={"photo": (name, fh, claimed)})
print(name, r.status_code, r.json())
photo.jpg 201 {'filename': 'photo.jpg', 'content_type_claimed': 'image/jpeg', 'format': 'JPEG', 'original_size': [1600, 1067], 'size': [1600, 1067], 'bytes': 86666, 'transparent': False}
fake.jpg 400 {'detail': 'not a supported image (JPEG, PNG, WebP, GIF or AVIF)'}
truncated.jpg 400 {'detail': 'image file is damaged (image file is truncated (39 bytes not processed))'}
Uploads need the python-multipart package. await photo.read(MAX_BYTES + 1) reads at most one byte more
than the limit, so a huge upload is refused without being held in memory in full. The content_type_claimed field shows
why the claimed type is worthless: the fake file arrived as image/jpeg too. process_upload is CPU-bound;
in an async endpoint that handles many large photos, run it with await run_in_threadpool(process_upload, data)
so it does not block the event loop. (Recent Starlette versions warn that the httpx-based test client is deprecated;
the example hides that warning, which concerns only tests.)
Django: forms, the .image trap, and storage
import django
from django.conf import settings
settings.configure(STORAGES={"default": {"BACKEND": "django.core.files.storage.InMemoryStorage"}})
django.setup()
from django import forms
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image
from uploads import BadImage, process_upload
class PhotoForm(forms.Form):
photo = forms.ImageField() # Django checks the file with Pillow's verify()
def handle(uploaded):
form = PhotoForm(files={"photo": uploaded})
if not form.is_valid():
return "form error: " + form.errors["photo"][0]
f = form.cleaned_data["photo"]
print(" f.image after validation:", type(f.image).__name__, f.image.size)
try:
f.image.resize((10, 10))
except Exception as e:
print(" f.image.resize():", type(e).__name__, "- verify() leaves this image unusable")
f.seek(0)
try:
webp, info = process_upload(f.read()) # read the upload again, then process it
except BadImage as e:
return "rejected: " + str(e)
name = default_storage.save("photos/upload.webp", ContentFile(webp))
return f"saved {name}: {Image.open(default_storage.open(name)).size}"
for name in ["phone_gps.jpg", "fake.jpg", "big.png", "bomb.png"]:
print(name)
print(" ", handle(SimpleUploadedFile(name, open(name, "rb").read(), content_type="image/jpeg")))
phone_gps.jpg
f.image after validation: JpegImageFile (1200, 800)
f.image.resize(): AssertionError - verify() leaves this image unusable
saved photos/upload.webp: (800, 1200)
fake.jpg
form error: Upload a valid image. The file you uploaded was either not an image or a corrupted image.
big.png
f.image after validation: PngImageFile (10000, 10000)
f.image.resize(): AssertionError - verify() leaves this image unusable
rejected: image is too large (10000 x 10000 pixels)
bomb.png
form error: Upload a valid image. The file you uploaded was either not an image or a corrupted image.
/home/you/.venv/lib/python3.13/site-packages/PIL/Image.py:3593: DecompressionBombWarning: Image size (100000000 pixels) exceeds limit of 89478485 pixels, could be decompression bomb DOS attack.
warnings.warn(
Django's ImageField validates uploads by opening them with Pillow and calling verify(), then attaches
that image as f.image. After verify() a Pillow image cannot be loaded or resized, which is why
f.image.resize() fails above. Use f.image only to read the format and size; for processing, seek back and
read the file again. Django's validation rejects the fake file and the bomb (Pillow raises while opening it), but the
100-megapixel big.png passes it with only a warning, and nothing is stripped or resized, so the
process_upload step is still needed. With a model, save the processed bytes into the field:
import io
from django.core.files.base import ContentFile
from PIL import Image
from uploads import process_upload
# models.py
# class Photo(models.Model):
# original = models.ImageField(upload_to="originals/")
# web = models.ImageField(upload_to="web/", blank=True)
def save_web_version(photo):
photo.original.open("rb")
webp, info = process_upload(photo.original.read())
photo.web.save(f"{photo.pk}.webp", ContentFile(webp), save=True) # writes the file and the model row
If Django says it cannot use ImageField because Pillow is not installed, see
that error's page.
Storing on S3
import io
import boto3
from moto import mock_aws # a local fake of AWS, so this runs without an account
from PIL import Image
from uploads import process_upload
with mock_aws():
s3 = boto3.client("s3", region_name="eu-west-1")
s3.create_bucket(Bucket="photos", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"})
webp, info = process_upload(open("phone_gps.jpg", "rb").read())
s3.upload_fileobj(io.BytesIO(webp), "photos", "web/42.webp",
ExtraArgs={"ContentType": "image/webp", "CacheControl": "public, max-age=31536000"})
obj = s3.get_object(Bucket="photos", Key="web/42.webp")
print("stored:", obj["ContentType"], obj["ContentLength"], "bytes")
img = Image.open(io.BytesIO(obj["Body"].read())) # and back: S3 bytes straight into Pillow
print("read back:", img.format, img.size)
stored: image/webp 70978 bytes
read back: WEBP (800, 1200)
upload_fileobj() takes the in-memory bytes directly, so nothing touches the local disk. Set
ContentType, or browsers download the file instead of showing it; a long CacheControl is safe when each
upload gets a new key. The test runs against moto, a local fake of AWS; with real credentials the same code talks to S3.
Reading back works the same way in reverse: the body bytes go straight into Image.open(io.BytesIO(...)).
Serving images back
To return a generated image from a view without writing a file, save into io.BytesIO and send its bytes with the
right content type; see image to bytes and base64. To accept images from URLs
instead of uploads, see opening images from URLs and bytes.
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:
- Django: forms ImageField
- Flask: uploading files
- FastAPI: request files
- boto3: S3 upload_fileobj
- Pillow documentation: Image
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.