67 lines
2.9 KiB
Python
67 lines
2.9 KiB
Python
import os
|
||
from pathlib import Path
|
||
import struct
|
||
import zlib
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
SAMPLE_PNG = (ROOT / 'tests' / 'fixtures' / 'sample.png').read_bytes()
|
||
SAMPLE_JPG = (Path(__file__).resolve().parent / 'fixtures' / 'sample.jpg').read_bytes()
|
||
|
||
|
||
def chunk(kind, data):
|
||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff)
|
||
|
||
|
||
def png(width, height, rows, color_type=0, level=9):
|
||
"""rows — итератор байтовых строк пикселей (без байта фильтра)."""
|
||
compressor = zlib.compressobj(level)
|
||
parts = []
|
||
for row in rows:
|
||
parts.append(compressor.compress(b'\x00' + row))
|
||
parts.append(compressor.flush())
|
||
header = struct.pack('>IIBBBBB', width, height, 8, color_type, 0, 0, 0)
|
||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
|
||
|
||
|
||
def bomb(width=10000, height=5000):
|
||
"""50 Мп чёрного: в распакованном виде 50 МБ, в файле — несколько десятков КБ."""
|
||
row = bytes(width)
|
||
return png(width, height, (row for _ in range(height)))
|
||
|
||
|
||
def noise_png(target_bytes):
|
||
"""Шумный RGB PNG (почти не сжимается) размером чуть меньше target_bytes."""
|
||
width = 1024
|
||
height = max(1, (target_bytes - 4096) // (width * 3 + 1))
|
||
return png(width, height, (os.urandom(width * 3) for _ in range(height)), color_type=2, level=0)
|
||
|
||
|
||
def broken_crc(data):
|
||
"""Испортить один байт внутри IDAT, не пересчитывая CRC."""
|
||
position = data.index(b'IDAT') + 100
|
||
return data[:position] + bytes([data[position] ^ 0xff]) + data[position + 1:]
|
||
|
||
|
||
def with_idat(data, transform):
|
||
"""Заменить пиксельные данные PNG (все IDAT) на transform(idat), с правильными CRC."""
|
||
position, chunks = 8, []
|
||
while position < len(data):
|
||
length, kind = struct.unpack('>I4s', data[position:position + 8])
|
||
chunks.append((kind, data[position + 8:position + 8 + length]))
|
||
position += 12 + length
|
||
idat = b''.join(body for kind, body in chunks if kind == b'IDAT')
|
||
first = next(index for index, (kind, _) in enumerate(chunks) if kind == b'IDAT')
|
||
kept = [(kind, body) for kind, body in chunks if kind != b'IDAT']
|
||
kept.insert(first, (b'IDAT', transform(idat)))
|
||
return data[:8] + b''.join(chunk(kind, body) for kind, body in kept)
|
||
|
||
|
||
def garbage_idat(data):
|
||
"""Мусор вместо сжатых пикселей, CRC верные."""
|
||
return with_idat(data, lambda idat: idat[:2] + os.urandom(len(idat) - 2))
|
||
|
||
|
||
def short_idat(data):
|
||
"""Корректный zlib-поток, но пикселей меньше, чем требует IHDR."""
|
||
return with_idat(data, lambda idat: zlib.compress(zlib.decompress(idat)[:-500]))
|