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

+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