{"record":{"id":"c3a88899ec7b3496","repo":"unslothai/unsloth","slug":"invalid-base64-image-data-exc","errorCode":null,"errorMessage":"Invalid base64 image data: {exc}","messagePattern":"Invalid base64 image data: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":400,"severity":"error","filePath":"studio/backend/core/inference/diffusion.py","lineNumber":375,"sourceCode":"    \"\"\"Decode a base64 (optionally ``data:`` URL) image string to a PIL image.\n\n    The image-conditioned workflows (img2img / inpaint / edit) transport the input\n    image and mask as base64 in the JSON request, so this is the single decode path.\n    A mask is decoded as single-channel ``L``; the source image as ``RGB``.\"\"\"\n    import base64\n    import binascii\n    import io\n\n    from PIL import Image\n\n    raw = data.strip()\n    if raw.startswith(\"data:\"):\n        # data:[<mime>][;base64],<payload>\n        _, _, raw = raw.partition(\",\")\n    try:\n        blob = base64.b64decode(raw, validate = False)\n    except (binascii.Error, ValueError) as exc:\n        raise ValueError(f\"Invalid base64 image data: {exc}\") from exc\n    # Bound the decoded size: 4096px covers txt2img 2048, upscales and outpaint canvases.\n    max_side = 4096\n    try:\n        img = Image.open(io.BytesIO(blob))\n        # Reject from the header before img.load() so a huge-dimension file cannot spike memory.\n        w, h = img.size\n        if w > max_side or h > max_side:\n            raise ValueError(f\"Image is too large ({w}x{h}); maximum is {max_side}px per side.\")\n        img.load()\n    except ValueError:\n        raise  # the size guard's own message; don't wrap it as a decode error\n    except Exception as exc:  # noqa: BLE001 — surfaced as a 400 to the client\n        raise ValueError(f\"Could not decode image: {exc}\") from exc\n    return img.convert(mode)\n\n\ndef _snap_to_multiple(img: Any, multiple: int = 16) -> Any:\n    \"\"\"Resize a PIL image so both sides are multiples of ``multiple`` (rounded to nearest,","sourceCodeStart":357,"sourceCodeEnd":393,"githubUrl":"https://github.com/unslothai/unsloth/blob/203007d19051dcd2ae33876786d117c99f6b0368/studio/backend/core/inference/diffusion.py#L357-L393","documentation":"Raised while parsing a client-supplied image (img2img/inpaint/outpaint/upscale base) when base64.b64decode raises binascii.Error or ValueError: the payload after stripping a data: URL prefix is not valid base64. It surfaces to the client as a 400.","triggerScenarios":"Truncated or whitespace-mangled base64 string; payload containing characters outside the base64 alphabet; a data: URL whose header portion was included because it lacked the ',' separator handled by partition; JSON-escaped newlines corrupting the string.","commonSituations":"Frontend truncating large images in JSON; copy-paste of base64 with line breaks; double-encoding (base64 of base64); sending a raw file URL where bytes are expected.","solutions":["Regenerate the payload: strip whitespace/newlines, and re-encode the source image with base64.b64encode","Send as a proper data URL 'data:image/png;base64,<payload>' — the parser handles the prefix","Verify the client is not truncating large request bodies (check proxy/server max body size)"],"exampleFix":"# before\nopen(\"img.png\", \"rb\").read()  # raw bytes sent as text\n\n# after\nbase64.b64encode(open(\"img.png\", \"rb\").read()).decode()","handlingStrategy":"validation","validationCode":"import base64, binascii\ndef valid_b64_image_payload(data: str) -> bool:\n    raw = data.strip()\n    if raw.startswith(\"data:\"):\n        raw = raw.partition(\",\")[2]\n    try:\n        base64.b64decode(raw, validate=False)\n        return True\n    except (binascii.Error, ValueError):\n        return False","typeGuard":null,"tryCatchPattern":"try:\n    img = parse_b64_image(data)\nexcept ValueError as e:\n    if \"Invalid base64\" in str(e):\n        return JSONResponse(status_code=400, content={\"detail\": str(e)})","preventionTips":["Strip whitespace/newlines from base64 before sending","Encode with a standard library (PIL save → base64.b64encode), never hand-copied blobs","Check server/proxy max request body size for large images"],"tags":["diffusion","image","base64","validation","client-error"],"backgroundTag":null,"analyzedSha":"203007d19051dcd2ae33876786d117c99f6b0368","analyzedAt":"2026-08-15T02:48:39.846Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}