{"record":{"id":"59406cc9d8353a47","repo":"AUTOMATIC1111/stable-diffusion-webui","slug":"invalid-image-url","errorCode":null,"errorMessage":"Invalid image url","messagePattern":"Invalid image url","errorType":"http","errorClass":"HTTPException","httpStatus":500,"severity":"error","filePath":"modules/api/api.py","lineNumber":91,"sourceCode":"\n    return True\n\n\ndef decode_base64_to_image(encoding):\n    if encoding.startswith(\"http://\") or encoding.startswith(\"https://\"):\n        if not opts.api_enable_requests:\n            raise HTTPException(status_code=500, detail=\"Requests not allowed\")\n\n        if opts.api_forbid_local_requests and not verify_url(encoding):\n            raise HTTPException(status_code=500, detail=\"Request to local resource not allowed\")\n\n        headers = {'user-agent': opts.api_useragent} if opts.api_useragent else {}\n        response = requests.get(encoding, timeout=30, headers=headers)\n        try:\n            image = images.read(BytesIO(response.content))\n            return image\n        except Exception as e:\n            raise HTTPException(status_code=500, detail=\"Invalid image url\") from e\n\n    if encoding.startswith(\"data:image/\"):\n        encoding = encoding.split(\";\")[1].split(\",\")[1]\n    try:\n        image = images.read(BytesIO(base64.b64decode(encoding)))\n        return image\n    except Exception as e:\n        raise HTTPException(status_code=500, detail=\"Invalid encoded image\") from e\n\n\ndef encode_pil_to_base64(image):\n    with io.BytesIO() as output_bytes:\n        if isinstance(image, str):\n            return image\n        if opts.samples_format.lower() == 'png':\n            use_metadata = False\n            metadata = PngImagePlugin.PngInfo()\n            for key, value in image.info.items():","sourceCodeStart":73,"sourceCodeEnd":109,"githubUrl":"https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/82a973c04367123ae98bd9abdf80d9eda9b910e2/modules/api/api.py#L73-L109","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Fetch the same URL with curl/the client and inspect Content-Type and first bytes; fix the link or authenticate properly","Set Settings -> API -> api_useragent to a browser-like UA if the host blocks default python-requests","Re-download client-side, validate with PIL, then POST the image as base64"],"exampleFix":"# before: blind URL pass-through\njson={'init_images':['https://example.com/maybe-image']}\n\n# after: validate then send base64\nfrom PIL import Image\nfrom io import BytesIO\nimport base64, requests\nr = requests.get('https://example.com/maybe-image', timeout=30)\nimg = Image.open(BytesIO(r.content)); img.load()  # raises early if not an image\njson={'init_images':[base64.b64encode(r.content).decode()]}","handlingStrategy":"validation","validationCode":"from PIL import Image\nfrom io import BytesIO\ndef b64_from_validated_url(u: str, ua: str='Mozilla/5.0') -> str | None:\n    r = requests.get(u, timeout=30, headers={'user-agent': ua})\n    try:\n        img = Image.open(BytesIO(r.content)); img.load()\n    except Exception:\n        return None\n    return base64.b64encode(r.content).decode()","typeGuard":"def looks_like_image_bytes(b: bytes) -> bool:\n    return b[:8] == b'\\x89PNG\\r\\n\\x1a\\n' or b[:3] == b'\\xff\\xd8\\xff' or b[:4] == b'RIFF'","tryCatchPattern":"if resp.status_code == 500 and resp.json()['detail'] == 'Invalid image url':\n    b64 = b64_from_validated_url(url)\n    if b64 is None: raise RuntimeError('source URL does not serve a decodable image')\n    payload['init_images'] = [b64]; resp = requests.post(url_, json=payload, auth=auth)","preventionTips":["Validate remote images client-side with PIL before POSTing","Set a browser-like api_useragent when fetching from CDNs","Check Content-Type headers of fetched URLs during development"],"tags":["api","network","image-decoding","http-500","stable-diffusion-webui"],"backgroundTag":null,"analyzedSha":"82a973c04367123ae98bd9abdf80d9eda9b910e2","analyzedAt":"2026-08-14T16:46:43.225Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}