Generating WebP sizes when images are uploaded

Images make up most of the bytes a browser downloads on a portfolio. Sending a 4MB JPEG to a phone over cellular data slows page loads and wastes bandwidth.

Third-party image CDNs solve resizing, yet they add external billing, extra DNS lookups, and another service that can fail. For this portfolio, I built a self-hosted image pipeline inside the Django model layer.

The Upload Pipeline

After I upload an image in Django admin, the model runs three steps:

  1. Content Hashing: I hash the file bytes with SHA-256 to create a collision-resistant name.
  2. Derivative Generation: I normalize orientation with Pillow's ImageOps.exif_transpose, resize to 480px, 960px, and 1600px widths, and encode WebP files at 82% quality.
  3. Metadata Storage: I save the generated paths and dimensions in a JSONField on the record.
def generate_image_variants(instance):
    # Generates 480w, 960w, and 1600w WebP derivatives
    # Stores results in instance.image_variants

HTML Output

My templates render a standard srcset with matching sizes:

<img src="/media/variants/project/abc/960.webp"
     srcset="/media/variants/project/abc/480.webp 480w,
             /media/variants/project/abc/960.webp 960w,
             /media/variants/project/abc/1600.webp 1600w"
     sizes="(max-width: 820px) 100vw, 1200px"
     alt="Project preview" loading="lazy">

The browser picks the smallest variant that fits the screen, with zero third-party image hosts.

← Journal