AUTOMATIC1111/stable-diffusion-webui · error · HTTPException

Invalid image url

Error message

Invalid image url

What it means

HTTP 500 raised by decode_base64_to_image when remote fetching is enabled, the URL passed verification, requests.get succeeded, but the response body could not be parsed as an image by PIL (images.read / BytesIO). This wraps whatever decode error PIL raised, so the fetch itself worked while the payload was not a decodable picture.

Source

Thrown at modules/api/api.py:91

    return True


def decode_base64_to_image(encoding):
    if encoding.startswith("http://") or encoding.startswith("https://"):
        if not opts.api_enable_requests:
            raise HTTPException(status_code=500, detail="Requests not allowed")

        if opts.api_forbid_local_requests and not verify_url(encoding):
            raise HTTPException(status_code=500, detail="Request to local resource not allowed")

        headers = {'user-agent': opts.api_useragent} if opts.api_useragent else {}
        response = requests.get(encoding, timeout=30, headers=headers)
        try:
            image = images.read(BytesIO(response.content))
            return image
        except Exception as e:
            raise HTTPException(status_code=500, detail="Invalid image url") from e

    if encoding.startswith("data:image/"):
        encoding = encoding.split(";")[1].split(",")[1]
    try:
        image = images.read(BytesIO(base64.b64decode(encoding)))
        return image
    except Exception as e:
        raise HTTPException(status_code=500, detail="Invalid encoded image") from e


def encode_pil_to_base64(image):
    with io.BytesIO() as output_bytes:
        if isinstance(image, str):
            return image
        if opts.samples_format.lower() == 'png':
            use_metadata = False
            metadata = PngImagePlugin.PngInfo()
            for key, value in image.info.items():

View on GitHub (pinned to 82a973c043)

Solutions

  1. Fetch the same URL with curl/the client and inspect Content-Type and first bytes; fix the link or authenticate properly
  2. Set Settings -> API -> api_useragent to a browser-like UA if the host blocks default python-requests
  3. Re-download client-side, validate with PIL, then POST the image as base64

Example fix

# before: blind URL pass-through
json={'init_images':['https://example.com/maybe-image']}

# after: validate then send base64
from PIL import Image
from io import BytesIO
import base64, requests
r = requests.get('https://example.com/maybe-image', timeout=30)
img = Image.open(BytesIO(r.content)); img.load()  # raises early if not an image
json={'init_images':[base64.b64encode(r.content).decode()]}
Defensive patterns

Strategy: validation

Validate before calling

from PIL import Image
from io import BytesIO
def b64_from_validated_url(u: str, ua: str='Mozilla/5.0') -> str | None:
    r = requests.get(u, timeout=30, headers={'user-agent': ua})
    try:
        img = Image.open(BytesIO(r.content)); img.load()
    except Exception:
        return None
    return base64.b64encode(r.content).decode()

Type guard

def looks_like_image_bytes(b: bytes) -> bool:
    return b[:8] == b'\x89PNG\r\n\x1a\n' or b[:3] == b'\xff\xd8\xff' or b[:4] == b'RIFF'

Try / catch

if resp.status_code == 500 and resp.json()['detail'] == 'Invalid image url':
    b64 = b64_from_validated_url(url)
    if b64 is None: raise RuntimeError('source URL does not serve a decodable image')
    payload['init_images'] = [b64]; resp = requests.post(url_, json=payload, auth=auth)

Prevention

When it happens

Trigger: img2img/interrogate request with a URL returning HTML (error page, redirect to login), a truncated or zero-byte body, an unsupported/corrupt format, or a content-type mismatch; timeout=30 applies to the GET, so slow-but-successful responses with garbage bodies still land here.

Common situations: Signed/expired CDN links returning XML errors; URLs behind auth walls returning login pages; sites hotlink-protected (mitigated partly by api_useragent); partially downloaded files over flaky connections.

Related errors


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