{"record":{"id":"09cdb0560bbff274","repo":"AUTOMATIC1111/stable-diffusion-webui","slug":"invalid-encoded-image","errorCode":null,"errorMessage":"Invalid encoded image","messagePattern":"Invalid encoded image","errorType":"http","errorClass":"HTTPException","httpStatus":500,"severity":"error","filePath":"modules/api/api.py","lineNumber":99,"sourceCode":"\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():\n                if isinstance(key, str) and isinstance(value, str):\n                    metadata.add_text(key, value)\n                    use_metadata = True\n            image.save(output_bytes, format=\"PNG\", pnginfo=(metadata if use_metadata else None), quality=opts.jpeg_quality)\n\n        elif opts.samples_format.lower() in (\"jpg\", \"jpeg\", \"webp\"):\n            if image.mode in (\"RGBA\", \"P\"):\n                image = image.convert(\"RGB\")","sourceCodeStart":81,"sourceCodeEnd":117,"githubUrl":"https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/82a973c04367123ae98bd9abdf80d9eda9b910e2/modules/api/api.py#L81-L117","documentation":"HTTP 500 raised by decode_base64_to_image when the payload was not a URL or data: URI and base64.b64decode + PIL images.read failed on it. This is the path for plain base64-encoded image strings; any exception in decoding (binascii.Error for bad base64 alphabet/padding, PIL UnidentifiedImageError for non-image bytes) is wrapped into this detail.","triggerScenarios":"img2img init_images or interrogate image containing malformed base64 (missing padding, data-URI prefix not stripped because the prefix wasn't exactly 'data:image/', whitespace/newlines from JSON copying, or raw binary bytes base64'd twice); valid base64 of a non-image file (e.g. a PDF).","commonSituations":"Frontends that paste base64 with newlines; double-encoding (base64 of base64); sending a data URI with unusual prefix like 'data:application/octet-stream' which skips the split branch and then fails decode; files exported with different formats (webp/avif) the local Pillow build can't read.","solutions":["Validate the string client-side: re.decode + base64.b64decode with validate=True, then PIL.Image.open before sending","If sending a data URI, use the canonical 'data:image/png;base64,....' form so the split branch strips it","Ensure single base64 encoding and strip whitespace/newlines: b64 = b64.replace('\\n','').strip()","Update/verify Pillow supports the encoded format (avif/webp extras)"],"exampleFix":"# before\nb64 = open('img.png','rb').read().hex()  # wrong: hex, not base64\n\n# after\nimport base64\nb64 = base64.b64encode(open('img.png','rb').read()).decode()\nrequests.post(url+'/sdapi/v1/img2img', json={'init_images':[b64]})","handlingStrategy":"validation","validationCode":"import base64\nfrom PIL import Image\nfrom io import BytesIO\ndef valid_image_b64(path: str) -> str:\n    img = Image.open(path); img.load()  # rejects non-images early\n    return base64.b64encode(open(path,'rb').read()).decode()\n# additionally: base64.b64decode(s, validate=True) round-trip check","typeGuard":"def is_valid_b64_image(s: str) -> bool:\n    try:\n        img = Image.open(BytesIO(base64.b64decode(s, validate=True))); img.load()\n        return True\n    except Exception:\n        return False","tryCatchPattern":"if resp.status_code == 500 and 'Invalid encoded image' in resp.json()['detail']:\n    raise ValueError('payload was not valid base64 image bytes') from None  # fix upstream data, don't retry","preventionTips":["Strip whitespace/newlines from base64 before sending","Use data:image/png;base64, prefix form if sending data URIs","Encode exactly once; verify with a b64decode round-trip in tests"],"tags":["api","base64","image-decoding","http-500","validation","stable-diffusion-webui"],"backgroundTag":null,"analyzedSha":"82a973c04367123ae98bd9abdf80d9eda9b910e2","analyzedAt":"2026-08-14T16:46:43.225Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}