Skip to content

Used of stdlib module removed in python 3.13 #466

@m3at

Description

@m3at

Hi, thanks for the useful tool,

imghdr, used in the resizer, has been removed in python3.13.
We could use one of the recommended external library, but as we only care about 3 file types (webp / jpg / png afaict) we could just check the first few bytes?

This is enough to check if it's in one of those three image types:

from typing import Optional, Union, BinaryIO

def what_img_ext(src: Union[bytes, bytearray, memoryview, BinaryIO]) -> Optional[str]:
    if isinstance(src, (bytes, bytearray, memoryview)):
        h = bytes(src[:12])
    else:
        if not (hasattr(src, "seek") and hasattr(src, "tell")):
            return None
        pos = src.tell()
        h = src.read(12)
        src.seek(pos)

    if h.startswith(b"\xFF\xD8\xFF"):
        return "jpeg"
    if h.startswith(b"\x89PNG\r\n\x1a\n"):
        return "png"
    if len(h) >= 12 and h[0:4] == b"RIFF" and h[8:12] == b"WEBP":
        return "webp"
    return None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions