forked from mtusi2026/mtusi2026lab5
94 lines
4.5 KiB
Python
94 lines
4.5 KiB
Python
"""Синтетические изображения для тестов вложений: только стандартная библиотека.
|
||
|
||
PNG собирается вручную (сигнатура, IHDR, IDAT, IEND), поэтому можно получить любой размер
|
||
в пикселях и байтах, а также испортить конкретный байт. JPEG берётся из fixtures/.
|
||
"""
|
||
import os
|
||
import struct
|
||
import zlib
|
||
from pathlib import Path
|
||
|
||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||
MAX_PIXELS = 40_000_000
|
||
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||
|
||
|
||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||
|
||
|
||
def png(width, height, *, gray=False, noise=False, interlace=0, pad_to=None, idat=None) -> bytes:
|
||
"""PNG width x height. noise=True — случайные пиксели (почти не сжимаются, файл большой).
|
||
|
||
pad_to — дополнить файл текстовым чанком tEXt после IDAT до точного размера в байтах.
|
||
idat — готовые сжатые данные (для «бомбы»: заголовок обещает одно, данных другое).
|
||
"""
|
||
channels = 1 if gray else 3
|
||
header = struct.pack(">IIBBBBB", width, height, 8, 0 if gray else 2, 0, 0, interlace)
|
||
if idat is None:
|
||
compressor = zlib.compressobj(6)
|
||
parts = []
|
||
# Adam7: 7 проходов, у каждого свои ширина и высота; без interlace — один проход.
|
||
passes = [(width, height)] if not interlace else [
|
||
((width - x + dx - 1) // dx, (height - y + dy - 1) // dy) for x, y, dx, dy in ADAM7]
|
||
for pass_width, pass_height in passes:
|
||
if pass_width <= 0 or pass_height <= 0:
|
||
continue
|
||
row = b"\x00" + bytes(pass_width * channels)
|
||
for _ in range(pass_height):
|
||
parts.append(compressor.compress(b"\x00" + os.urandom(pass_width * channels) if noise else row))
|
||
parts.append(compressor.flush())
|
||
idat = b"".join(parts)
|
||
body = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", idat)
|
||
if pad_to is not None:
|
||
need = pad_to - len(body) - 12 - 12 - 8 # заголовок чанка-заполнителя, IEND, ключ "Comment\0"
|
||
assert need >= 0, "image is already larger than pad_to"
|
||
body += chunk(b"tEXt", b"Comment\x00" + b"a" * need)
|
||
return body + chunk(b"IEND", b"")
|
||
|
||
|
||
def noise_png(target_bytes: int) -> bytes:
|
||
"""Почти несжимаемый PNG размером чуть меньше target_bytes (квадрат RGB со случайными пикселями)."""
|
||
side = int(((target_bytes - 4096) / 3) ** 0.5)
|
||
return png(side, side, noise=True)
|
||
|
||
|
||
def sample_png() -> bytes:
|
||
return (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||
|
||
|
||
def sample_jpeg() -> bytes:
|
||
return (FIXTURES / "sample.jpg").read_bytes()
|
||
|
||
|
||
def progressive_jpeg() -> bytes:
|
||
return (FIXTURES / "progressive.jpg").read_bytes()
|
||
|
||
|
||
def flip_byte(data: bytes, position: int) -> bytes:
|
||
return data[:position] + bytes([data[position] ^ 0xFF]) + data[position + 1:]
|
||
|
||
|
||
GIF = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"
|
||
|
||
|
||
# --- сборка PNG из произвольных чанков (для проверок смысла чанков при верных CRC) ---
|
||
|
||
def ihdr(width, height, depth=8, color=2, interlace=0):
|
||
return b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)
|
||
|
||
|
||
def zero_idat(width, height, depth=8, channels=3):
|
||
"""Сжатые пиксели: каждая строка = байт фильтра 0 + нули (индекс палитры 0 / чёрный)."""
|
||
row_bytes = (width * depth * channels + 7) // 8
|
||
return b"IDAT", zlib.compress((b"\x00" + bytes(row_bytes)) * height)
|
||
|
||
|
||
def assemble(*chunks):
|
||
"""PNG из чанков (kind, data) с ВЕРНЫМИ CRC; IEND добавляется, если не передан."""
|
||
if not chunks or chunks[-1][0] != b"IEND":
|
||
chunks = chunks + ((b"IEND", b""),)
|
||
return b"\x89PNG\r\n\x1a\n" + b"".join(chunk(kind, data) for kind, data in chunks)
|