52 行
1.7 KiB
Python
52 行
1.7 KiB
Python
"""Supported raster image signature, MIME, and extension mappings."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ImageFormat:
|
|
mime_type: str
|
|
extension: str
|
|
accepted_extensions: frozenset[str]
|
|
|
|
|
|
PNG = ImageFormat("image/png", ".png", frozenset({".png"}))
|
|
JPEG = ImageFormat("image/jpeg", ".jpg", frozenset({".jpg", ".jpeg"}))
|
|
GIF = ImageFormat("image/gif", ".gif", frozenset({".gif"}))
|
|
WEBP = ImageFormat("image/webp", ".webp", frozenset({".webp"}))
|
|
|
|
SUPPORTED_IMAGE_FORMATS = (PNG, JPEG, GIF, WEBP)
|
|
SUPPORTED_IMAGE_MIME_TYPES = frozenset(item.mime_type for item in SUPPORTED_IMAGE_FORMATS)
|
|
SUPPORTED_IMAGE_EXTENSIONS = frozenset(
|
|
extension for item in SUPPORTED_IMAGE_FORMATS for extension in item.accepted_extensions
|
|
)
|
|
IMAGE_EXTENSIONS_BY_MIME = {
|
|
item.mime_type: item.accepted_extensions for item in SUPPORTED_IMAGE_FORMATS
|
|
}
|
|
|
|
|
|
def detect_image_format(content: bytes) -> ImageFormat | None:
|
|
"""Return the supported image format identified by its file signature."""
|
|
|
|
if content.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
return PNG
|
|
if content.startswith(b"\xff\xd8\xff"):
|
|
return JPEG
|
|
if content.startswith((b"GIF87a", b"GIF89a")):
|
|
return GIF
|
|
if len(content) >= 12 and content.startswith(b"RIFF") and content[8:12] == b"WEBP":
|
|
return WEBP
|
|
return None
|
|
|
|
|
|
def detect_file_image_format(path: Path) -> ImageFormat | None:
|
|
"""Inspect only the bytes required to identify a supported image file."""
|
|
|
|
try:
|
|
with path.open("rb") as handle:
|
|
return detect_image_format(handle.read(12))
|
|
except OSError:
|
|
return None
|