Resizing Images
NotesThe header of the theme ideally takes an image of 1900x600. Rather than relying on people to upload images of the right size, use Pillow, the Python imaging library, to crop and resize them on upload. As a bonus, opening the upload with Pillow also proves it really is an image, whatever its file name says.
Install the Python pillow package:
pip install pillowInclude it in non_ver_reqs.txt:
non_ver_reqs.txttext
fastapi[standard]
pydantic-settings
pytest
sqlmodel
alembic
markdown
nh3
pillowpip freeze > requirements.txtBecause uploads are handled in one place, only the helper needs to change. Here is the complete web/images.py:
web/images.pypython
import io
import uuid
from pathlib import Path
from fastapi import HTTPException, UploadFile, status
from PIL import Image, ImageOps, UnidentifiedImageError
from config.settings import settings
COVER_IMAGE_SIZE = (1900, 600)
MAX_UPLOAD_BYTES = 10 * 1024 * 1024 # 10 MB
def save_cover_image(upload: UploadFile) -> str:
"""Validate, crop/resize and save an uploaded cover image. Returns its URL path."""
data = upload.file.read(MAX_UPLOAD_BYTES + 1)
if len(data) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=status.HTTP_413_CONTENT_TOO_LARGE, detail="Image is too large.")
try:
image = Image.open(io.BytesIO(data))
image.load()
except (UnidentifiedImageError, OSError):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Upload is not a valid image.")
# Respect the camera's orientation, then crop to fill the header without distortion
image = ImageOps.exif_transpose(image)
image = ImageOps.fit(image.convert("RGB"), COVER_IMAGE_SIZE)
# Never trust the uploaded file name: generate our own
filename = f"{uuid.uuid4()}.jpg"
upload_dir = Path(settings.CONF_IMAGE_UPLOADS_FILE_PATH)
upload_dir.mkdir(parents=True, exist_ok=True)
image.save(upload_dir / filename, "JPEG", quality=85)
return settings.CONF_IMAGE_UPLOADS_CONTEXT_PATH + filenameStepping through it:
- The upload is read into memory, up to a limit of 10 MB. Anything bigger is rejected with
413 Content Too Large, so nobody can fill your disk or memory with one request. Image.open()andimage.load()fail for anything that isn’t a real image, which is rejected with a400. That makes the extension check from the previous section unnecessary.ImageOps.exif_transpose()rotates photos the right way up. Phones often store portrait photos sideways, with a note in the image’s EXIF data saying how to rotate them.ImageOps.fit()scales the image to cover 1900x600, then crops off whatever doesn’t fit, keeping the centre.img.resize((1900, 600))would instead stretch or squash it, distorting anything that isn’t already the right shape.convert("RGB")handles PNGs with transparency (JPEG has no transparency), and everything is saved as a JPEG at quality 85, a good balance of size and quality. The resized image is the only file written, so there’s no original to clean up.
The views don’t change at all: they still call save_cover_image().