xtekky/gpt4free · error · ValueError

Invalid image format or file not found. Expected bytes, str,

Error message

Invalid image format or file not found. Expected bytes, str, or PIL Image. Got: {image[:100]}

What it means

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.

Source

Thrown at g4f/image/__init__.py:481

                    raise FileNotFoundError(f"File not found: {path}")
            else:
                if not is_safe_url(image):
                    raise ValueError("Invalid or unsafe image url")
                resp = requests.get(
                    image,
                    headers={
                        "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",
                    },
                )
                if resp.ok and is_accepted_format(resp.content):
                    return resp.content
                raise ValueError(
                    "Invalid image url. Expected bytes, str, or PIL Image."
                )
        elif os.path.exists(image):
            return Path(image).read_bytes()
        else:
            raise ValueError(
                f"Invalid image format or file not found. Expected bytes, str, or PIL Image. Got: {image[:100]}"
            )
    elif isinstance(image, Image.Image):
        bytes_io = BytesIO()
        image.save(bytes_io, image.format)
        image.seek(0)
        return bytes_io.getvalue()
    elif isinstance(image, os.PathLike):
        return Path(image).read_bytes()
    elif isinstance(image, Path):
        return image.read_bytes()
    else:
        try:
            image.seek(0)
        except (AttributeError, io.UnsupportedOperation):
            pass
        return image.read()

View on GitHub (pinned to 973504e177)

Solutions

  1. If the image is base64 text, prefix it: f"data:image/png;base64,{b64_text}".
  2. If it is a local file, verify it exists first: os.path.isfile(image) and pass an absolute path via os.path.abspath().
  3. 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).
  4. Alternatively pass bytes (open(p,'rb').read()), a pathlib.Path, or a PIL Image, which are all handled by other branches.

Example fix

// before
image = "C:\\Users\\me\\pic.png"  # or raw base64 string
result = to_bytes(image)

// after
image = "data:image/png;base64," + b64_text  # for base64
# or
image = Path("/abs/path/pic.png")
result = to_bytes(image)
Defensive patterns

Strategy: type-guard

Validate before calling

from g4f.image import to_bytes
import os

def valid_image_source(image) -> bool:
    if isinstance(image, (bytes, Path, os.PathLike)):
        return True
    if isinstance(image, str):
        return (
            image.startswith("data:")
            or image.startswith(("http://", "https://"))
            or os.path.isfile(image)
        )
    return hasattr(image, "read")

Type guard

def is_valid_image_type(image) -> bool:
    import os
    from pathlib import Path
    from PIL import Image
    return (
        isinstance(image, (bytes, bytearray, str, Path, os.PathLike, Image.Image))
        or hasattr(image, "read")
    ) and (
        not isinstance(image, str)
        or image.startswith(("data:", "http://", "https://"))
        or os.path.isfile(image)
    )

Try / catch

try:
    data = to_bytes(image)
except ValueError as e:
    if "Invalid image format" in str(e):
        raise ValueError(f"unsupported image source: {image!r:.80}") from e
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/a98cfcfbea469d4d. Report an issue: GitHub.