58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
import struct
|
|
import zlib
|
|
from io import BytesIO
|
|
from pathlib import Path
|
|
|
|
from PIL import Image
|
|
|
|
SAMPLE = (Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png").read_bytes()
|
|
SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
|
|
|
|
def chunk(kind: bytes, data: bytes) -> bytes:
|
|
crc = zlib.crc32(kind + data)
|
|
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", crc)
|
|
|
|
|
|
def png_from_idat(
|
|
data: bytes,
|
|
width: int = 1,
|
|
height: int = 1,
|
|
*,
|
|
depth: int = 8,
|
|
color: int = 2,
|
|
interlace: int = 0,
|
|
chunk_size: int = 65_536,
|
|
) -> bytes:
|
|
header = struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)
|
|
palette = chunk(b"PLTE", bytes(range(256)) * 3) if color == 3 else b""
|
|
blocks = [
|
|
chunk(b"IDAT", data[start : start + chunk_size])
|
|
for start in range(0, len(data), chunk_size)
|
|
]
|
|
return SIGNATURE + chunk(b"IHDR", header) + palette + b"".join(blocks) + chunk(b"IEND", b"")
|
|
|
|
|
|
BROKEN_PNG = png_from_idat(b"not a zlib stream")
|
|
|
|
|
|
def png(width: int, height: int, *, size: int | None = None, rows: bool = True) -> bytes:
|
|
header = struct.pack(">IIBBBBB", width, height, 1, 0, 0, 0, 0)
|
|
raw = (b"\x00" * (1 + (width + 7) // 8)) * height if rows else b"\x00"
|
|
head = SIGNATURE + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(raw, 9))
|
|
tail = chunk(b"IEND", b"")
|
|
if size is not None:
|
|
head += chunk(b"prVt", b"\x00" * (size - len(head) - len(tail) - 12))
|
|
return head + tail
|
|
|
|
|
|
def encoded(kind: str, width: int = 640, height: int = 480) -> bytes:
|
|
buffer = BytesIO()
|
|
Image.effect_noise((width, height), 64).convert("RGB").save(buffer, kind)
|
|
return buffer.getvalue()
|
|
|
|
|
|
JPEG = encoded("JPEG")
|
|
GIF = encoded("GIF")
|
|
WEBP = encoded("WEBP")
|