AUTOMATIC1111/stable-diffusion-webui · error · HTTPException

Invalid image format

Error message

Invalid image format

What it means

HTTP 500 raised by encode_pil_to_base64 when returning generated images: the server serializes output images according to opts.samples_format, and if that setting is a value other than png/jpg/jpeg/webp (e.g. 'avif', a typo, or an unset/empty string) no save branch matches and the response cannot be built. It reflects an invalid server-side output format configuration, not a bad request.

Source

Thrown at modules/api/api.py:128

                if isinstance(key, str) and isinstance(value, str):
                    metadata.add_text(key, value)
                    use_metadata = True
            image.save(output_bytes, format="PNG", pnginfo=(metadata if use_metadata else None), quality=opts.jpeg_quality)

        elif opts.samples_format.lower() in ("jpg", "jpeg", "webp"):
            if image.mode in ("RGBA", "P"):
                image = image.convert("RGB")
            parameters = image.info.get('parameters', None)
            exif_bytes = piexif.dump({
                "Exif": { piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(parameters or "", encoding="unicode") }
            })
            if opts.samples_format.lower() in ("jpg", "jpeg"):
                image.save(output_bytes, format="JPEG", exif = exif_bytes, quality=opts.jpeg_quality)
            else:
                image.save(output_bytes, format="WEBP", exif = exif_bytes, quality=opts.jpeg_quality)

        else:
            raise HTTPException(status_code=500, detail="Invalid image format")

        bytes_data = output_bytes.getvalue()

    return base64.b64encode(bytes_data)


def api_middleware(app: FastAPI):
    rich_available = False
    try:
        if os.environ.get('WEBUI_RICH_EXCEPTIONS', None) is not None:
            import anyio  # importing just so it can be placed on silent list
            import starlette  # importing just so it can be placed on silent list
            from rich.console import Console
            console = Console()
            rich_available = True
    except Exception:
        pass

View on GitHub (pinned to 82a973c043)

Solutions

  1. Set Settings -> Saving to a directory -> File format for images to one of png, jpg, jpeg, or webp, or remove the key from config.json to restore the 'png' default
  2. Restart the server after fixing config.json if editing by hand
  3. If you need avif, convert client-side from the png base64 the API returns

Example fix

# before: config.json
"samples_format": "avif"

# after
"samples_format": "png"
Defensive patterns

Strategy: validation

Validate before calling

opts = requests.get(f'{base}/sdapi/v1/options', auth=auth).json()
assert opts.get('samples_format','png') in ('png','jpg','jpeg','webp'), f"server samples_format invalid: {opts.get('samples_format')}"

Type guard

def samples_format_ok(fmt: str | None) -> bool:
    return (fmt or 'png') in ('png','jpg','jpeg','webp')

Prevention

When it happens

Trigger: Any successful /sdapi/v1/txt2img, img2img, or extras call when Settings -> Saving to a directory -> 'File format for images' (samples_format) has been set to an unsupported extension; default is 'png', so this only fires after configuration changes or config-file hand-edits.

Common situations: Users setting samples_format to 'avif' or 'jpeg2000' which the encoder branch doesn't handle; hand-edited config.json with a typo; stale settings after webui versions that renamed the option.

Related errors


AI-assisted analysis of AUTOMATIC1111/stable-diffusion-webui@82a973c043 (2026-08-14). Data as JSON: /api/errors/9d634bd7436d7a5f. Report an issue: GitHub.