imgA-simple: image/ico (ICO/CUR: 1-32 bit DIBs + AND masks, PNG entries via opts.decodeImage / encodeImage, hotspots) against Pillow

This commit is contained in:
4DBug committed 2026-10-31 08:54:33 -05:00
1 parent 4f6f14604b
commit 4123df462b
6 files changed
+617

No files matched your search

+1
View File
@@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` |
| image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` |
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` |
| image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` |
+12
View File
@@ -26,6 +26,18 @@ local list: { Entry } = {
return require("@formats/image/hdr")
end,
},
{
name = "ico",
category = "image",
path = "image/ico",
extensions = { "ico", "cur" },
mime = { "image/vnd.microsoft.icon", "image/x-icon" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
load = function()
return require("@formats/image/ico")
end,
},
{
name = "png",
category = "image",
+106
View File
@@ -0,0 +1,106 @@
--!strict
--!native
--!optimize 2
-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from
-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit
-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha
-- channel unless it is all zero (old icons), in which case the AND mask decides.
local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32
local Dib = {}
-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out
function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?)
local stride = ((w * bpp + 31) // 32) * 4
local maskStride = ((w + 31) // 32) * 4
if p + stride * h > e then
return false, "colour bitmap runs past the entry"
end
local hasMask = p + stride * h + maskStride * h <= e
local anyAlpha = false
for y = 0, h - 1 do
local row = p + (h - 1 - y) * stride
for x = 0, w - 1 do
local v
if bpp == 32 then
v = readu8(b, row + x * 4 + 2) + readu8(b, row + x * 4 + 1) * 256 + readu8(b, row + x * 4) * 65536 + readu8(b, row + x * 4 + 3) * 16777216
if v >= 16777216 then
anyAlpha = true
end
elseif bpp == 24 then
v = readu8(b, row + x * 3 + 2) + readu8(b, row + x * 3 + 1) * 256 + readu8(b, row + x * 3) * 65536 + 0xFF000000
elseif bpp == 16 then
local s = readu16(b, row + x * 2)
local r, g, bl = (s // 1024) % 32, (s // 32) % 32, s % 32
v = (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + 0xFF000000
else
local bit = x * bpp
local byte = readu8(b, row + bit // 8)
local idx = (byte // 2 ^ (8 - bpp - bit % 8)) % 2 ^ bpp
v = if idx < palN then readu32(pal, idx * 4) else 0xFF000000
end
writeu32(out, (y * w + x) * 4, v)
end
end
if bpp == 32 and anyAlpha then
return true, nil
end
if hasMask then
local mp = p + stride * h
for y = 0, h - 1 do
local row = mp + (h - 1 - y) * maskStride
for x = 0, w - 1 do
local o = (y * w + x) * 4
local px = readu32(out, o) % 16777216
if (readu8(b, row + x // 8) // 2 ^ (7 - x % 8)) % 2 == 1 then
writeu32(out, o, px) -- transparent
else
writeu32(out, o, px + 0xFF000000)
end
end
end
elseif bpp == 32 then
-- no alpha and no mask: opaque
for i = 0, w * h - 1 do
writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000)
end
end
return true, nil
end
-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1).
-- out needs room for w * h * 4 + maskStride * h bytes.
function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number
for y = h - 1, 0, -1 do
for x = 0, w - 1 do
local q = (y * w + x) * 4
buffer.writeu8(out, o, readu8(px, q + 2))
buffer.writeu8(out, o + 1, readu8(px, q + 1))
buffer.writeu8(out, o + 2, readu8(px, q))
buffer.writeu8(out, o + 3, readu8(px, q + 3))
o += 4
end
end
local maskStride = ((w + 31) // 32) * 4
for y = h - 1, 0, -1 do
local acc, nb, written = 0, 0, 0
for x = 0, w - 1 do
acc = acc * 2 + (if readu8(px, (y * w + x) * 4 + 3) == 0 then 1 else 0)
nb += 1
if nb == 8 then
buffer.writeu8(out, o + written, acc)
written += 1
acc, nb = 0, 0
end
end
if nb > 0 then
buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb))
written += 1
end
buffer.fill(out, o + written, 0, maskStride - written)
o += maskStride
end
return o
end
return Dib
+282
View File
@@ -0,0 +1,282 @@
--!strict
-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every
-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or
-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are
-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest);
-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png
-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as
-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it
-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot.
-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS
-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Dib = require("@formats/image/ico/Dib")
-- ------------------------------------------------------------------------------------------------ contract
local Ico = {
name = "ico",
category = "image",
extensions = { "ico", "cur" },
mime = { "image/vnd.microsoft.icon", "image/x-icon" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
maxPixels: number?, -- refuse larger entries (default 2^26)
}
export type EncodeOptions = {
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists)
cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot)
}
-- ------------------------------------------------------------------------------------------------ constants
local PNG_SIG = "\137PNG\r\n\26\n"
local readu8 = buffer.readu8
-- ------------------------------------------------------------------------------------------------ sniff
function Ico.sniff(r: Bytes.Reader): number
if r:remaining() < 22 then
return 0
end
local b, o = r.buf, r.pos
local typ = buffer.readu16(b, o + 2)
local count = buffer.readu16(b, o + 4)
if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then
return 0
end
-- the first entry: reserved byte 0, a size and offset inside the file
local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18)
if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then
return 0
end
return 0.8
end
-- ------------------------------------------------------------------------------------------------ decode
local function le16(b: buffer, p: number): number
return buffer.readu16(b, p)
end
local function le32(b: buffer, p: number): number
return buffer.readu32(b, p)
end
function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local decodeImage = opts and opts.decodeImage
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 6 then
return nil, Err.new(Err.TRUNCATED, "short header", base)
end
local typ, count = le16(b, base + 2), le16(b, base + 4)
if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then
return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base)
end
if count == 0 then
return nil, Err.new(Err.CORRUPT, "no images", base)
end
if base + 6 + count * 16 > limit then
return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base)
end
local frames: { Types.Frame } = {}
local best: Types.Image? = nil
local bestScore = -1
local skipped, lastErr = 0, nil :: Err.Err?
for i = 0, count - 1 do
local d = base + 6 + i * 16
local dw, dh = readu8(b, d), readu8(b, d + 1)
dw = if dw == 0 then 256 else dw
dh = if dh == 0 then 256 else dh
local f1, f2 = le16(b, d + 4), le16(b, d + 6)
local size, off = le32(b, d + 8), le32(b, d + 12)
local p, e = base + off, base + off + size
local img: Types.Image? = nil
local depth = 0
local isPng = false
if off < 6 or p >= limit then
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d)
else
e = math.min(e, limit)
if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then
isPng = true
depth = 32
if decodeImage then
local sub = buffer.create(e - p)
buffer.copy(sub, 0, b, p, e - p)
local ok, pimg, perr = pcall(decodeImage, sub)
if ok and pimg and pimg.format == "rgba8" then
img = pimg
else
lastErr = if ok and perr then perr else Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG")
end
else
lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)")
end
elseif e - p >= 40 then
local hs = le32(b, p)
local bw = buffer.readi32(b, p + 4)
local bh = buffer.readi32(b, p + 8)
local bpp = le16(b, p + 14)
local clrUsed = le32(b, p + 32)
local w = if bw > 0 then bw else dw
local h = if bh ~= 0 then math.abs(bh) // 2 else dh
if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then
lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p)
elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then
lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p)
elseif w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
else
depth = bpp
local q = p + hs
local palN = 0
local pal = buffer.create(4)
if bpp <= 8 then
palN = if clrUsed > 0 and clrUsed < 2 ^ bpp then clrUsed else 2 ^ bpp
if q + palN * 4 > e then
palN = 0
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q)
else
pal = buffer.create(palN * 4)
for k = 0, palN - 1 do
local c = q + k * 4
buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000)
end
q += palN * 4
end
end
if bpp > 8 or palN > 0 then
if bpp == 16 and le32(b, p + 16) == 3 then
q += 12 -- BI_BITFIELDS masks (assumed 5-5-5)
end
local out = Types.Image.new(w, h, "rgba8")
local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels)
if ok then
img = out
else
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q)
end
end
end
else
lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p)
end
end
if img then
local im = img :: Types.Image
im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) }
if typ == 2 then
im.meta.hotspot = { x = f1, y = f2 }
end
table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" })
local score = im.width * im.height * 64 + depth
if score > bestScore then
best, bestScore = im, score
end
else
skipped += 1
end
end
if not best then
return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry")
end
local main = best :: Types.Image
local img = Types.Image.new(main.width, main.height, "rgba8")
buffer.copy(img.pixels, 0, main.pixels)
if #frames > 1 then
img.frames = frames
end
img.meta.source = { format = "ico", type = if typ == 2 then "cur" else "ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png }
img.meta.hotspot = main.meta.hotspot
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Ico.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local o: any = opts or {}
local list: { Types.Image } = {}
if type(img.frames) == "table" and #img.frames > 0 then
for _, f in img.frames do
table.insert(list, f.image)
end
else
list[1] = img
end
local cursor = o.cursor
if cursor == nil then
cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil
end
local blobs: { buffer } = {}
for i, im in list do
if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image")
end
local w, h = im.width, im.height
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then
return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side")
end
local png = nil
if o.encodeImage and (o.png or w == 256 or h == 256) then
local ok, res, err = pcall(o.encodeImage, im, "png")
if not ok or not res then
return nil, if ok and err then err else Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed")
end
png = res
elseif o.png then
return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)")
end
if png then
blobs[i] = png
else
local maskStride = ((w + 31) // 32) * 4
local n = 40 + w * h * 4 + maskStride * h
local d = buffer.create(n)
buffer.writeu32(d, 0, 40)
buffer.writei32(d, 4, w)
buffer.writei32(d, 8, h * 2)
buffer.writeu16(d, 12, 1)
buffer.writeu16(d, 14, 32)
buffer.writeu32(d, 20, w * h * 4 + maskStride * h)
Dib.encode(im.pixels, w, h, d, 40)
blobs[i] = d
end
end
local total = 6 + #list * 16
for _, bl in blobs do
total += buffer.len(bl)
end
local out = buffer.create(total)
buffer.writeu16(out, 2, if cursor then 2 else 1)
buffer.writeu16(out, 4, #list)
local off = 6 + #list * 16
for i, im in list do
local d = 6 + (i - 1) * 16
buffer.writeu8(out, d, im.width % 256)
buffer.writeu8(out, d + 1, im.height % 256)
if cursor then
local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 }
buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535))
buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535))
else
buffer.writeu16(out, d + 4, 1)
buffer.writeu16(out, d + 6, 32)
end
buffer.writeu32(out, d + 8, buffer.len(blobs[i]))
buffer.writeu32(out, d + 12, off)
buffer.copy(out, off, blobs[i])
off += buffer.len(blobs[i])
end
return out, nil
end
return Ico
+123
View File
@@ -0,0 +1,123 @@
-- image/ico tests: ImageMagick- and Pillow-written icons (PNG and BMP entries, a 256 PNG entry) and hand-built ones
-- (1 / 4 / 8 / 24 / 32-bit DIBs with AND masks, a cursor with hotspots) against Pillow's decode of every entry; PNG
-- entries through opts.decodeImage (and UNSUPPORTED without it); the main image is the largest entry; our encoder
-- (DIB, PNG through opts.encodeImage, cursors) round-trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/ico.py.
local T = require("@tests/T")
local Ico = require("@formats/image/ico")
local Png = require("@formats/image/png")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/ico")
local t = T.suite("ico")
t:eq(Ico.name, "ico", "name")
t:check(Ico.caps.decode and Ico.caps.encode, "caps")
local hooks = {
decodeImage = function(b: buffer)
return Png.decode(Bytes.reader(b))
end,
encodeImage = function(img: any, _fmt: string)
return Png.encode(img)
end,
}
local function dec(data: any, opts: any?): (any, any)
return Ico.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
end
local entries = 0
for _, c in Fx do
local img, err = dec(c.data, hooks)
t:check(img, c.name .. ": " .. tostring(err))
local frames = img.frames or { { image = img } }
t:eq(#frames, #c.entries, c.name .. ": entry count")
local biggest = 0
for i, e in c.entries do
local f = frames[i].image
t:check(f.width == e.width and f.height == e.height, string.format("%s entry %d: size %dx%d, want %dx%d", c.name, i, f.width, f.height, e.width, e.height))
local worst = 0
for k = 0, #e.rgba - 1 do
worst = math.max(worst, math.abs(buffer.readu8(f.pixels, k) - string.byte(e.rgba, k + 1)))
end
t:check(worst == 0, string.format("%s entry %d: differs from Pillow by %d", c.name, i, worst))
biggest = math.max(biggest, e.width * e.height)
entries += 1
end
t:eq(img.width * img.height, biggest, c.name .. ": the main image is the largest entry")
-- round trip through our encoder (DIB entries, and PNG for 256 through the hook)
local enc, eerr = Ico.encode(img, hooks)
t:check(enc, c.name .. ": encode: " .. tostring(eerr))
local back = dec(enc, hooks)
local bf = back.frames or { { image = back } }
t:eq(#bf, #frames, c.name .. ": round trip entries")
for i, f in frames do
local a, b = f.image, bf[i].image
local same = a.width == b.width and a.height == b.height
if same then
-- alpha-0 pixels keep their colour in 32-bit DIBs too
same = buffer.tostring(a.pixels) == buffer.tostring(b.pixels)
end
t:check(same, string.format("%s: round trip entry %d", c.name, i))
end
end
t:note("%d icons, %d entries match Pillow and round-trip", #Fx, entries)
do
local byName = {}
for _, c in Fx do
byName[c.name] = c
end
-- without the hook: PNG entries are skipped, BMP entries still decode
local big, sm = Types.Image.new(256, 256), Types.Image.new(16, 16)
buffer.fill(big.pixels, 0, 77, 256 * 256 * 4)
buffer.fill(sm.pixels, 0, 99, 16 * 16 * 4)
local two = Types.Image.new(256, 256)
two.frames = { { image = big, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = sm, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } }
local mixed = Ico.encode(two, hooks) :: buffer
t:eq(buffer.readstring(mixed, 6 + 32, 4), "\137PNG", "the 256 entry is written as PNG through the hook")
local im = dec(mixed)
t:check(im and im.width == 16 and im.meta.source.skipped == 1, "no hook: the PNG entry is skipped")
t:eq(dec(mixed, hooks).width, 256, "with the hook: the PNG entry is the main image")
local _, e = dec(byName["pil-png"].data)
t:check(e and e.code == Err.UNSUPPORTED, "PNG-only icon without the hook: " .. tostring(e))
local cur = dec(byName["hand-cur"].data)
t:check(cur.meta.source.type == "cur" and cur.meta.hotspot and cur.meta.hotspot.x == 3 and cur.meta.hotspot.y == 4, "cursor hotspot")
t:eq(cur.frames[2].image.meta.hotspot.x, 5, "second hotspot")
local cenc = Ico.encode(cur) :: buffer
t:eq(buffer.readu16(cenc, 2), 2, "cursor written as CUR")
local cb = dec(cenc)
t:check(cb.meta.hotspot.x == 3 and cb.frames[2].image.meta.hotspot.y == 6, "hotspots round-trip")
-- PNG entries on request
local small = Types.Image.new(16, 16)
buffer.fill(small.pixels, 0, 200, 16 * 16 * 4)
local pe = Ico.encode(small, { png = true, encodeImage = hooks.encodeImage }) :: buffer
t:eq(buffer.readstring(pe, 22, 4), "\137PNG", "opts.png writes a PNG entry")
local _, e2 = Ico.encode(small, { png = true })
t:check(e2 and e2.code == Err.ARG, "opts.png without a hook")
local _, e3 = Ico.encode(Types.Image.new(300, 10))
t:check(e3 and e3.code == Err.ARG, "over 256 pixels")
t:eq(Ico.sniff(Bytes.reader(buffer.fromstring(byName["pil-bmp"].data))), 0.8, "sniff")
t:eq(Ico.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 30)))), 0, "sniff zeros")
local _, e4 = dec(string.sub(byName["pil-bmp"].data, 1, 20))
t:check(e4 and e4.code == Err.TRUNCATED, "truncated directory")
end
do
local samples = {}
for _, c in Fx do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Ico.decode(Bytes.reader(b), hooks)
end, samples)
t:fuzz("decode without hooks", function(b: buffer)
return Ico.decode(Bytes.reader(b))
end, samples, { mutations = 3, garbage = 50 })
end
t:done()
+93
View File
@@ -0,0 +1,93 @@
# ICO / CUR fixtures (tools/fixtures.py): icons written by ImageMagick (auto-resize sets with a 256 PNG entry) and
# Pillow (PNG and BMP entries), and hand-built ones from Pillow's BMP writer (1 / 4 / 8 / 24 / 32-bit DIBs with AND
# masks, a cursor with hotspots); references = Pillow's RGBA decode of every entry, in file order.
# tests/gen/ico.luau { { name, data, entries = { { width, height, rgba (bytes) } } } }
import struct
CODE = r'''
import io, struct, subprocess, sys
from PIL import Image, IcoImagePlugin
magick = sys.argv[1]
out = []
def refs(data):
if data[2] == 2: # IcoFile reads icons only: decode a cursor's entries as an icon's
data = data[:2] + b"\x01" + data[3:]
f = IcoImagePlugin.IcoFile(io.BytesIO(data))
order = sorted(range(len(f.entry)), key=lambda i: f.entry[i].offset)
res = []
for i in order:
im = f.frame(i).convert("RGBA")
res.append((im.size[0], im.size[1], im.tobytes()))
return res
def emit(name, data):
out.append((name, data, refs(data)))
src = Image.new("RGBA", (64, 64))
px = src.load()
for y in range(64):
for x in range(64):
a = 255 if (x - 32) ** 2 + (y - 32) ** 2 < 900 else (0 if x < 8 else 128)
px[x, y] = ((x * 4) % 256, (y * 4) % 256, ((x ^ y) * 8) % 256, a)
png = io.BytesIO(); src.save(png, "PNG")
r = subprocess.run([magick, "png:-", "-define", "icon:auto-resize=256,48,32,16", "ico:-"], input=png.getvalue(), capture_output=True, check=True)
emit("im-autoresize", r.stdout)
for fmt in ("png", "bmp"):
b = io.BytesIO(); src.save(b, "ICO", sizes=[(16, 16), (32, 32), (64, 64)], bitmap_format=fmt); emit("pil-" + fmt, b.getvalue())
# hand-built DIB entries from Pillow BMPs
def dib(im, mask_fn):
b = io.BytesIO(); im.save(b, "BMP"); d = b.getvalue()[14:]
w, h = im.size
hs = struct.unpack("<I", d[:4])[0]
d = d[:8] + struct.pack("<i", h * 2) + d[12:]
stride = ((w + 31) // 32) * 4
mask = bytearray()
for y in range(h - 1, -1, -1):
row = bytearray(stride)
for x in range(w):
if mask_fn(x, y):
row[x // 8] |= 0x80 >> (x % 8)
mask += row
return d + bytes(mask)
def icon(entries, typ=1, hotspots=None):
hdr = struct.pack("<HHH", 0, typ, len(entries))
off = 6 + 16 * len(entries)
dirs, blobs = b"", b""
for i, (im, blob, bpp) in enumerate(entries):
w, h = im.size
f1, f2 = (1, bpp) if typ == 1 else hotspots[i]
dirs += struct.pack("<BBBBHHII", w % 256, h % 256, 0, 0, f1, f2, len(blob), off)
off += len(blob); blobs += blob
return hdr + dirs + blobs
base = src.resize((24, 20))
m = lambda x, y: (x + y) % 7 == 0
e1 = base.convert("1"); e4 = base.convert("RGB").quantize(16); e8 = base.convert("RGB").quantize(200); e24 = base.convert("RGB")
emit("hand-dibs", icon([(e1, dib(e1, m), 1), (e4, dib(e4, m), 4), (e8, dib(e8, m), 8), (e24, dib(e24, m), 24)]))
e32 = src.resize((30, 17))
b = io.BytesIO(); e32.save(b, "BMP"); d32 = b.getvalue()[14:]
# Pillow writes 32-bit BMPs as BGRA? if not, build one by hand
w, h = e32.size
bgra = b"".join(bytes((p[2], p[1], p[0], p[3])) for y in range(h - 1, -1, -1) for p in (e32.getpixel((x, y)) for x in range(w)))
stride = ((w + 31) // 32) * 4
d32 = struct.pack("<IiiHHIIiiII", 40, w, h * 2, 1, 32, 0, len(bgra), 0, 0, 0, 0) + bgra + bytes(stride * h)
emit("hand-32", icon([(e32, d32, 32)]))
emit("hand-cur", icon([(e24, dib(e24, m), 24), (e8, dib(e8, m), 8)], typ=2, hotspots=[(3, 4), (5, 6)]))
for name, data, rs in out:
sys.stdout.buffer.write(struct.pack("<HIH", len(name), len(data), len(rs)) + name.encode() + data)
for w, h, px in rs:
sys.stdout.buffer.write(struct.pack("<III", w, h, len(px)) + px)
'''
def generate(ctx):
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
raw = ctx.python(["pillow"], CODE.replace("sys.argv[1]", repr(magick)))
cases, p = [], 0
while p < len(raw):
nl, dl, ne = struct.unpack("<HIH", raw[p:p + 8]); p += 8
name = raw[p:p + nl].decode(); p += nl
data = raw[p:p + dl]; p += dl
ents = []
for _ in range(ne):
w, h, pl = struct.unpack("<III", raw[p:p + 12]); p += 12
ents.append({"width": w, "height": h, "rgba": raw[p:p + pl]}); p += pl
cases.append({"name": name, "data": data, "entries": ents})
ctx.emit("ico", cases)