{"record":{"id":"a98cfcfbea469d4d","repo":"xtekky/gpt4free","slug":"invalid-image-format-or-file-not-found-expected-b","errorCode":null,"errorMessage":"Invalid image format or file not found. Expected bytes, str, or PIL Image. Got: {image[:100]}","messagePattern":"Invalid image format or file not found\\. Expected bytes, str, or PIL Image\\. Got: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"g4f/image/__init__.py","lineNumber":481,"sourceCode":"                    raise FileNotFoundError(f\"File not found: {path}\")\n            else:\n                if not is_safe_url(image):\n                    raise ValueError(\"Invalid or unsafe image url\")\n                resp = requests.get(\n                    image,\n                    headers={\n                        \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0\",\n                    },\n                )\n                if resp.ok and is_accepted_format(resp.content):\n                    return resp.content\n                raise ValueError(\n                    \"Invalid image url. Expected bytes, str, or PIL Image.\"\n                )\n        elif os.path.exists(image):\n            return Path(image).read_bytes()\n        else:\n            raise ValueError(\n                f\"Invalid image format or file not found. Expected bytes, str, or PIL Image. Got: {image[:100]}\"\n            )\n    elif isinstance(image, Image.Image):\n        bytes_io = BytesIO()\n        image.save(bytes_io, image.format)\n        image.seek(0)\n        return bytes_io.getvalue()\n    elif isinstance(image, os.PathLike):\n        return Path(image).read_bytes()\n    elif isinstance(image, Path):\n        return image.read_bytes()\n    else:\n        try:\n            image.seek(0)\n        except (AttributeError, io.UnsupportedOperation):\n            pass\n        return image.read()\n","sourceCodeStart":463,"sourceCodeEnd":499,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/image/__init__.py#L463-L499","documentation":"Thrown by g4f.image.to_bytes() when the input is a str that is neither a data: URI, an http(s) URL, nor an existing filesystem path, so no branch can produce bytes. The message echoes the first 100 chars of the input to show what was rejected. It is a pure input-validation error: the value's type is str, but its content matches no supported image source.","triggerScenarios":"Calling to_bytes() (directly or via image-capable providers) with a str that: has a typo in the path, points to a file that was deleted, uses a non-http scheme like 'ftp://' or 'file://', is a relative path evaluated from the wrong working directory, or is raw base64 without a 'data:image/...;base64,' prefix.","commonSituations":"Passing an absolute path valid on the developer's machine but not in a container/server cwd; passing base64 text without the data-URI wrapper; passing a Windows path with backslashes; passing an empty string after a failed upstream field extraction.","solutions":["If the image is base64 text, prefix it: f\"data:image/png;base64,{b64_text}\".","If it is a local file, verify it exists first: os.path.isfile(image) and pass an absolute path via os.path.abspath().","If it is remote, ensure the string starts with http:// or https:// and the URL returns an accepted image format (is_accepted_format must pass).","Alternatively pass bytes (open(p,'rb').read()), a pathlib.Path, or a PIL Image, which are all handled by other branches."],"exampleFix":"// before\nimage = \"C:\\\\Users\\\\me\\\\pic.png\"  # or raw base64 string\nresult = to_bytes(image)\n\n// after\nimage = \"data:image/png;base64,\" + b64_text  # for base64\n# or\nimage = Path(\"/abs/path/pic.png\")\nresult = to_bytes(image)","handlingStrategy":"type-guard","validationCode":"from g4f.image import to_bytes\nimport os\n\ndef valid_image_source(image) -> bool:\n    if isinstance(image, (bytes, Path, os.PathLike)):\n        return True\n    if isinstance(image, str):\n        return (\n            image.startswith(\"data:\")\n            or image.startswith((\"http://\", \"https://\"))\n            or os.path.isfile(image)\n        )\n    return hasattr(image, \"read\")","typeGuard":"def is_valid_image_type(image) -> bool:\n    import os\n    from pathlib import Path\n    from PIL import Image\n    return (\n        isinstance(image, (bytes, bytearray, str, Path, os.PathLike, Image.Image))\n        or hasattr(image, \"read\")\n    ) and (\n        not isinstance(image, str)\n        or image.startswith((\"data:\", \"http://\", \"https://\"))\n        or os.path.isfile(image)\n    )","tryCatchPattern":"try:\n    data = to_bytes(image)\nexcept ValueError as e:\n    if \"Invalid image format\" in str(e):\n        raise ValueError(f\"unsupported image source: {image!r:.80}\") from e\n    raise","preventionTips":["Always pass bytes or pathlib.Path for local files; str only for data URIs and http(s) URLs.","Wrap base64 payloads in a data:image/...;base64, prefix yourself.","Resolve local paths with os.path.abspath() before passing strings."],"tags":["image","input-validation","bytes"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}