Files

66 lines
3.2 KiB
Python

# ImageOps fixtures (tools/fixtures.py): Pillow references for ops/ImageOps.
# tests/gen/imageops.luau { rgb = { w, h, px }, rgba = {...}, rgba2 = {...}, gray = L bytes of rgb,
# resize = { { filter, mode, w, h, px } }, rotate = { { angle, expand, w, h, px } },
# composite = bytes }
# rgb / rgba: smooth gradients + noise + shapes (Pillow drawing), deterministic.
import struct
CODE = r'''
import random, struct, sys
from PIL import Image, ImageDraw
rng = random.Random(11)
def src(w, h, mode):
im = Image.new("RGBA", (w, h))
px = im.load()
for y in range(h):
for x in range(w):
px[x, y] = ((x * 255) // (w - 1), (y * 255) // (h - 1), (x * y) % 256, 255 if mode == "RGB" else (x * 7 + y * 3) % 256)
d = ImageDraw.Draw(im)
for _ in range(5):
x0, y0 = rng.randrange(w), rng.randrange(h)
d.ellipse([x0, y0, x0 + rng.randrange(4, 20), y0 + rng.randrange(4, 20)], fill=(rng.randrange(256), rng.randrange(256), rng.randrange(256), 255 if mode == "RGB" else rng.randrange(256)))
return im.convert(mode)
out = []
def emit(tag, *parts):
data = b"".join(parts)
out.append(struct.pack("<16sI", tag.encode().ljust(16), len(data)) + data)
rgb = src(61, 47, "RGB"); rgba = src(61, 47, "RGBA"); rgba2 = src(61, 47, "RGBA")
hdr = lambda im: struct.pack("<II", *im.size)
emit("rgb", hdr(rgb), rgb.tobytes()); emit("rgba", hdr(rgba), rgba.tobytes()); emit("rgba2", hdr(rgba2), rgba2.tobytes())
emit("gray", rgb.convert("L").tobytes())
emit("graya", rgba.convert("L").tobytes())
F = {"nearest": Image.NEAREST, "bilinear": Image.BILINEAR, "lanczos": Image.LANCZOS}
for fname, f in F.items():
for (w, h) in ((30, 20), (100, 80), (61, 20), (13, 47), (7, 3), (200, 150)):
for mode in ("RGB", "L"):
r = rgb.convert(mode).resize((w, h), f)
emit("resize", struct.pack("<16s4sII", fname.encode().ljust(16), mode.encode().ljust(4), w, h), r.tobytes())
for angle, expand in ((30, True), (-45, True), (123.4, True), (17, False), (200, False)):
r = rgba.rotate(angle, Image.BILINEAR, expand=expand)
emit("rotate", struct.pack("<dBII", angle, 1 if expand else 0, *r.size), r.tobytes())
emit("composite", Image.alpha_composite(rgba, rgba2).tobytes())
sys.stdout.buffer.write(b"".join(out))
'''
def generate(ctx):
raw = ctx.python(["pillow"], CODE)
p = 0
fx = {"resize": [], "rotate": []}
while p < len(raw):
tag, n = struct.unpack("<16sI", raw[p:p + 20]); p += 20
tag = tag.decode().strip()
data = raw[p:p + n]; p += n
if tag in ("rgb", "rgba", "rgba2"):
w, h = struct.unpack("<II", data[:8])
fx[tag] = {"w": w, "h": h, "px": data[8:]}
elif tag in ("gray", "graya", "composite"):
fx[tag] = data
elif tag == "resize":
f, mode, w, h = struct.unpack("<16s4sII", data[:28])
fx["resize"].append({"filter": f.decode().strip(), "mode": mode.decode().strip(), "w": w, "h": h, "px": data[28:]})
elif tag == "rotate":
a, e, w, h = struct.unpack("<dBII", data[:17])
fx["rotate"].append({"angle": a, "expand": bool(e), "w": w, "h": h, "px": data[17:]})
ctx.emit("imageops", fx)