BYTESLIP ← Back
Knowledge Base // Tutorial 118

Image SEO for Static Sites: AVIF, WebP, srcset and Alt Text With One Python Script

Difficulty: Easy ~30 min Python · Pillow · HTML

Phone photos are 3–5 MB, and article columns are about 720 px wide. This guide uses one Python script to make three sizes in three formats and print the <picture> markup with width, height, srcset and loading already filled in. Then we cover the parts Google uses to understand an image: the <img> element, the alt text, the filename and the text around it. In our test, a 1.6 MB public-domain USGS lava photo became a 72 KB AVIF at 960 px.

One photo to responsive, searchable images Four tiles: original photo, three formats, picture with srcset, alt text and filename. PHOTO 1.6 MB AVIF · WEBP · JPEG PICTURE + SRCSET ALT TEXT + FILENAME
Safety // Read First

Warnings

ImportantKeep your originals. The script writes new files into an out/ folder and never overwrites the source. It also strips EXIF, so GPS location in phone photos doesn’t end up on your site. If you want credit or license info shown in Google Images, add Google’s image metadata structured data instead.

Checklist // Before You Start

What You Need

How this was tested: Ran the script on Linux with Python 3.13 and Pillow 13.0.0 (AVIF on) and Python 3.14 with Pillow 13.0.0 (no AVIF, so the script fell back to WebP and JPEG). Source: “Molten Lava in Pahoehoe Skylight” (USGS, public domain, 2200 × 1466, 1.6 MB). Output at 960 px: AVIF 71.7 KB, WebP 164.1 KB, JPEG 176.5 KB. In headless Chrome at a 390 px viewport and 3× density, the browser picked the 1440 px AVIF, as the sizes rule intends.

Walkthrough // Steps 01–06

Install → convert → paste markup → alt text → check

Run it once per photo. It takes a few seconds on a tablet.

  1. Step 1: Install Python and Pillow

    pkg install python-pillow
    python3 -c "from PIL import features; print(features.check('avif'), features.check('webp'))"

    True True means both formats are available. If AVIF prints False, the script still works and makes WebP and JPEG only.

  2. Step 2: Save the script

    Save this as img_variants.py:

    #!/usr/bin/env python3
    """img_variants.py - make AVIF, WebP and JPEG sizes of one photo and print
    the <picture> markup for it (Byteslip).
    Usage: python3 img_variants.py photo.jpg "Alt text" [--hero]
    Needs Pillow. AVIF output only if your Pillow has AVIF support (otherwise WebP + JPEG)."""
    import os, sys
    from PIL import Image, ImageOps, features
    
    WIDTHS = (480, 960, 1440)
    SIZES = "(max-width: 768px) 100vw, 720px"   # matches a 720px-wide article column
    
    def main(src, alt, hero):
        im = ImageOps.exif_transpose(Image.open(src)).convert("RGB")  # honor phone rotation, drop EXIF
        stem = os.path.splitext(os.path.basename(src))[0].lower().replace(" ", "-")
        out = os.path.join(os.path.dirname(src) or ".", "out"); os.makedirs(out, exist_ok=True)
        fmts = [("avif", "AVIF", {"quality": 50})] if features.check("avif") else []
        fmts += [("webp", "WEBP", {"quality": 80, "method": 6}), ("jpg", "JPEG", {"quality": 82, "optimize": True, "progressive": True})]
        srcsets = {}
        for w in [w for w in WIDTHS if w <= im.width] or [im.width]:
            h = round(im.height * w / im.width)
            r = im.resize((w, h), Image.LANCZOS)
            for ext, fmt, opts in fmts:
                name = f"{stem}-{w}.{ext}"
                r.save(os.path.join(out, name), fmt, **opts)
                kb = os.path.getsize(os.path.join(out, name)) / 1024
                print(f"{name:32} {kb:7.1f} KB", file=sys.stderr)
                srcsets.setdefault(ext, []).append(f"{name} {w}w")
        big = max(w for w in WIDTHS if w <= im.width) if im.width >= WIDTHS[0] else im.width
        h = round(im.height * big / im.width)
        load = 'fetchpriority="high"' if hero else 'loading="lazy"'
        lines = ["<picture>"]
        for ext, mime in (("avif", "image/avif"), ("webp", "image/webp")):
            if ext in srcsets:
                lines.append(f'  <source type="{mime}" srcset="{", ".join(srcsets[ext])}" sizes="{SIZES}">')
        lines.append(f'  <img src="{stem}-{big}.jpg" srcset="{", ".join(srcsets["jpg"])}" sizes="{SIZES}"')
        lines.append(f'       width="{big}" height="{h}" alt="{alt}" {load} decoding="async">')
        lines.append("</picture>")
        print("\n".join(lines))
    
    if __name__ == "__main__":
        args = [a for a in sys.argv[1:] if a != "--hero"]
        if len(args) != 2: sys.exit(__doc__)
        main(args[0], args[1].replace('"', "&quot;"), "--hero" in sys.argv)

    It never upscales, it applies the phone’s rotation and then drops EXIF, and it turns the filename into lowercase-with-hyphens.

  3. Step 3: Name the file, then convert it

    Google says filenames give it very light clues, so molten-lava-skylight.jpg beats IMG_20261112.jpg. Rename first, then run:

    python3 img_variants.py "Molten Lava Skylight.jpg" "Molten lava glowing through a skylight in a pāhoehoe lava tube"

    The sizes go to stderr, and the markup goes to stdout:

    molten-lava-skylight-480.avif       19.2 KB
    molten-lava-skylight-960.avif       71.7 KB
    molten-lava-skylight-1440.avif     155.3 KB
    ... (WebP and JPEG lines too)
    <picture>
      <source type="image/avif" srcset="molten-lava-skylight-480.avif 480w, ..." sizes="(max-width: 768px) 100vw, 720px">
      <source type="image/webp" srcset="..." sizes="...">
      <img src="molten-lava-skylight-1440.jpg" srcset="..." sizes="..."
           width="1440" height="960" alt="Molten lava glowing ..." loading="lazy" decoding="async">
    </picture>

    Add --hero for the first, biggest image on the page. It swaps loading="lazy" for fetchpriority="high", because lazy-loading the LCP image slows the page.

  4. Step 4: Paste the markup and upload the files

    Google can find images in an <img> src (including inside <picture>), but it doesn’t index CSS background images. Google recommends always keeping a src fallback, because some crawlers don’t read srcset. The script does both.

    The browser picks the format through <source type>, so the server doesn’t have to. That matters on LiteSpeed shared hosting, where LiteSpeed’s docs list Apache’s content negotiation (mod_negotiation) as unsupported.

  5. Step 5: Write alt text and caption like a person

    Google uses alt text together with computer vision and the page’s content to understand an image, and calls keyword stuffing a bad experience that can look like spam.

    • Bad: alt="" on a meaningful photo, or alt="lava lava hawaii lava tube volcano lava".
    • Good: alt="Molten lava glowing through a skylight in a pāhoehoe lava tube".
    • Decorative images (dividers, background shapes) get alt="" so screen readers skip them.

    Put the image near the text that talks about it. If one image appears on several pages, always use the same URL so Google can reuse it.

  6. Step 6: Pick the preview image and check

    To suggest which image Google shows next to your result, set og:image or the schema.org primaryImageOfPage. Google recommends a relevant, high-resolution image, and not a generic logo or an image full of text. Then run PageSpeed Insights on the page and confirm there are no image-size warnings.

Pro Tip

Measure the column, not the screen

Questions // FAQ

FAQ

AVIF or WebP?

Use both. Google Search supports AVIF and WebP as well as JPEG, PNG, GIF, BMP and SVG. The picture element lets each browser pick the first format it supports, with the JPEG as the last fallback.

Do I need an image sitemap?

Only for images Google wouldn’t otherwise find. Google says an image sitemap helps with discovery and can list images on a CDN. Images in normal img tags on crawlable pages are usually found anyway.

Does the title attribute matter?

Google mentions captions and image titles as context it can use, but alt text is the most important attribute. A clear caption near the image helps readers too.

Will removing EXIF hurt SEO?

No Google image guidance requires EXIF. Removing it protects your location. If you want credit or license details shown in Google Images, use image metadata structured data instead.

Keep Reading
Sources // Verified

Official docs

Image discovery, srcset fallback, supported formats, alt text, filenames, and preferred image: Google image SEO best practices. Lazy loading and dimensions: Browser-level image lazy loading. Never lazy-load the LCP image: Optimize LCP. mod_negotiation unsupported on LiteSpeed: LiteSpeed Web Server configuration. AVIF support: Pillow image file formats. Photo: USGS, public domain, via Wikimedia Commons.

← All Tutorials Byteslip Apps