imgA-simple: image/tga (types 1/2/3/9/10/11, 8-32 bit, colour maps, origins; raw/RLE writer with TGA 2.0 footer) against Pillow / ImageMagick

This commit is contained in:
4DBug committed 2026-10-31 08:48:55 -05:00
1 parent 84c461f10d
commit f2e15af64d
6 files changed
+629

No files matched your search

+12
View File
@@ -50,6 +50,18 @@ local list: { Entry } = {
return require("@formats/image/qoi")
end,
},
{
name = "tga",
category = "image",
path = "image/tga",
extensions = { "tga", "icb", "vda", "vst", "tpic" },
mime = { "image/x-tga", "image/x-targa" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
load = function()
return require("@formats/image/tga")
end,
},
}
return list
+157
View File
@@ -0,0 +1,157 @@
--!strict
--!native
--!optimize 2
-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0
-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented
-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes.
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local Codec = {}
-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555,
-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them)
local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number
if kind == 0 then
return readu8(b, p) * 0x10101 + 0xFF000000
elseif kind == 1 then
return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000
elseif kind == 2 then
local v = readu16(b, p)
local r, g, bl = (v // 1024) % 32, (v // 32) % 32, v % 32
local a = if alpha1 and v < 32768 then 0 else 255
return (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick
elseif kind == 3 then
return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000
elseif kind == 4 then
return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216
end
local i = if kind == 5 then readu8(b, p) else readu16(b, p)
if i >= palN then
return 0xFF000000
end
return readu32(pal, i * 4)
end
Codec.pixel = pixel
-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated?
function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean)
local n = w * h
local i = 0
local function put(v: number)
local row, col = i // w, i % w
if bottomUp then
row = h - 1 - row
end
if rtl then
col = w - 1 - col
end
writeu32(out, (row * w + col) * 4, v)
i += 1
end
if not rle then
local avail = math.min(n, (limit - p) // bpp)
for _ = 1, avail do
put(pixel(b, p, kind, alpha1, pal, palN))
p += bpp
end
return i, avail < n
end
while i < n do
if p >= limit then
return i, true
end
local hd = readu8(b, p)
p += 1
local count = hd % 128 + 1
if hd >= 128 then
if p + bpp > limit then
return i, true
end
local v = pixel(b, p, kind, alpha1, pal, palN)
p += bpp
for _ = 1, math.min(count, n - i) do
put(v)
end
else
for _ = 1, math.min(count, n - i) do
if p + bpp > limit then
return i, true
end
put(pixel(b, p, kind, alpha1, pal, palN))
p += bpp
end
end
end
return i, false
end
-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1);
-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row.
-- out needs room for w * h * (outBpp + 1) bytes.
function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number
local function get(q: number): number
if srcBpp == 1 then
return readu8(px, q)
elseif srcBpp == 3 then
return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000
end
return readu32(px, q)
end
local function emit(v: number)
if outBpp == 1 then
writeu8(out, o, v % 256)
else
writeu8(out, o, (v // 65536) % 256)
writeu8(out, o + 1, (v // 256) % 256)
writeu8(out, o + 2, v % 256)
if outBpp == 4 then
writeu8(out, o + 3, v // 16777216)
end
end
o += outBpp
end
for y = 0, h - 1 do
local row = if topDown then y else h - 1 - y
local base = row * w * srcBpp
if not rle then
for x = 0, w - 1 do
emit(get(base + x * srcBpp))
end
else
local x = 0
while x < w do
local v = get(base + x * srcBpp)
local run = 1
while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do
run += 1
end
if run >= 2 then
writeu8(out, o, 127 + run)
o += 1
emit(v)
x += run
else
-- a raw packet up to the next run of 2 or more
local s = x
local cnt = 0
while x < w and cnt < 128 do
local c = get(base + x * srcBpp)
if x + 1 < w and get(base + (x + 1) * srcBpp) == c then
break
end
cnt += 1
x += 1
end
writeu8(out, o, cnt - 1)
o += 1
for k = s, s + cnt - 1 do
emit(get(base + k * srcBpp))
end
end
end
end
end
return o
end
return Codec
+276
View File
@@ -0,0 +1,276 @@
--!strict
-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3)
-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 /
-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left,
-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit:
-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data
-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit.
-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left
-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage
-- stamp, ...), which are ignored.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Codec = require("@formats/image/tga/Codec")
-- ------------------------------------------------------------------------------------------------ contract
local Tga = {
name = "tga",
category = "image",
extensions = { "tga", "icb", "vda", "vst", "tpic" },
mime = { "image/x-tga", "image/x-targa" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
}
export type EncodeOptions = {
rle: boolean?, -- run-length encode (default false)
origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands)
alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255)
id: string?, -- the image ID field (up to 255 bytes; default meta.text.id)
}
-- ------------------------------------------------------------------------------------------------ constants
local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true }
local FOOTER = "TRUEVISION-XFILE.\0"
local readu8 = buffer.readu8
-- ------------------------------------------------------------------------------------------------ sniff
type Header = {
idLen: number,
cmapType: number,
imageType: number,
cmapFirst: number,
cmapLen: number,
cmapBits: number,
width: number,
height: number,
depth: number,
desc: number,
}
local function header(r: Bytes.Reader): Header?
if r.limit - r.base < 18 then
return nil
end
local b, o = r.buf, r.base
local function u16(q: number): number
return readu8(b, o + q) + readu8(b, o + q + 1) * 256
end
local h: Header = {
idLen = readu8(b, o),
cmapType = readu8(b, o + 1),
imageType = readu8(b, o + 2),
cmapFirst = u16(3),
cmapLen = u16(5),
cmapBits = readu8(b, o + 7),
width = u16(12),
height = u16(14),
depth = readu8(b, o + 16),
desc = readu8(b, o + 17),
}
return h
end
-- plausible(h) -> nil | why not
local function implausible(h: Header): string?
local t = h.imageType
if not TYPES[t] then
return "image type " .. t
end
if h.cmapType > 1 then
return "colour map type " .. h.cmapType
end
local mapped = t == 1 or t == 9
if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then
return "colour-mapped image without a colour map"
end
if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then
return "colour map entry size " .. h.cmapBits
end
if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then
return "pixel depth " .. h.depth
end
if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then
return "grey pixel depth " .. h.depth
end
if h.width == 0 or h.height == 0 then
return "zero size"
end
if h.desc >= 64 then
return "interleaving / reserved descriptor bits"
end
return nil
end
function Tga.sniff(r: Bytes.Reader): number
local h = header(r)
if not h or implausible(h) then
return 0
end
local n = r.limit - r.base
if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then
return 0.9
end
return 0.2
end
-- ------------------------------------------------------------------------------------------------ decode
function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local h = header(r)
if not h then
return nil, Err.new(Err.TRUNCATED, "short header", r.base)
end
local why = implausible(h)
if why then
return nil, Err.new(if h.imageType == 0 then Err.UNSUPPORTED else Err.CORRUPT, why, r.base)
end
local w, ht = h.width, h.height
if w * ht > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels))
end
local b = r.buf
local p = r.base + 18
local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil
p += h.idLen
-- colour map
local pal = buffer.create(4)
local palN = 0
if h.cmapType == 1 and h.cmapLen > 0 then
local eb = (h.cmapBits + 7) // 8
if p + h.cmapLen * eb > r.limit then
return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p)
end
local first = h.cmapFirst
palN = first + h.cmapLen
pal = buffer.create(palN * 4)
buffer.fill(pal, 0, 0, palN * 4)
local kind = if h.cmapBits == 24 then 3 elseif h.cmapBits == 32 then 4 else 2
for i = 0, h.cmapLen - 1 do
buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0))
end
for i = 0, first - 1 do
buffer.writeu32(pal, i * 4, 0xFF000000)
end
p += h.cmapLen * eb
end
local t = h.imageType
local alphaBits = h.desc % 16
local kind
if t == 1 or t == 9 then
kind = if h.depth == 8 then 5 else 6
elseif t == 3 or t == 11 then
kind = if h.depth == 8 then 0 else 1
else
kind = if h.depth == 24 then 3 elseif h.depth == 32 then 4 else 2
end
local bpp = (h.depth + 7) // 8
local bottomUp = (h.desc // 32) % 2 == 0
local rtl = (h.desc // 16) % 2 == 1
local img = Types.Image.new(w, ht, "rgba8")
local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels)
local native = opts and opts.native
if native and kind == 0 then
local g = Types.Image.new(w, ht, "gray8")
for i = 0, w * ht - 1 do
buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4))
end
img = g
elseif native and kind == 3 then
local c = Types.Image.new(w, ht, "rgb8")
for i = 0, w * ht - 1 do
buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4))
buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2))
end
img = c
end
if palN > 0 then
local palette = {}
for i = 0, palN - 1 do
palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) }
end
img.meta.palette = palette
end
if id then
img.meta.text = { id = id }
end
if truncated then
img.meta.truncated = true
end
img.meta.source = {
format = "tga",
bitDepth = h.depth,
colorType = if kind >= 5 then "palette" elseif kind <= 1 then (if kind == 1 then "graya" else "gray") else (if kind == 3 then "rgb" else "rgba"),
rle = t >= 9,
origin = (if bottomUp then "bottom" else "top") .. "-" .. (if rtl then "right" else "left"),
alphaBits = alphaBits,
}
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Tga.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local srcBpp = if img.format == "rgba8" then 4 elseif img.format == "rgb8" then 3 elseif img.format == "gray8" then 1 else nil
if not srcBpp then
return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image")
end
local w, h = img.width, img.height
if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then
return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)")
end
local o: any = opts or {}
local origin = o.origin or "bottom-left"
if origin ~= "bottom-left" and origin ~= "top-left" then
return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"")
end
local outBpp = srcBpp
if srcBpp == 4 then
local alpha = o.alpha
if alpha == nil then
alpha = false
for i = 0, w * h - 1 do
if readu8(img.pixels, i * 4 + 3) ~= 255 then
alpha = true
break
end
end
end
outBpp = if alpha then 4 else 3
end
local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or ""
if type(id) ~= "string" then
id = ""
end
id = string.sub(id, 1, 255)
local rle = o.rle == true
local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26)
buffer.writeu8(out, 0, #id)
buffer.writeu8(out, 2, (if outBpp == 1 then 3 else 2) + (if rle then 8 else 0))
buffer.writeu16(out, 12, w)
buffer.writeu16(out, 14, h)
buffer.writeu8(out, 16, outBpp * 8)
buffer.writeu8(out, 17, (if outBpp == 4 then 8 else 0) + (if origin == "top-left" then 32 else 0))
buffer.writestring(out, 18, id)
local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id)
-- TGA 2.0 footer: no extension / developer areas
buffer.writeu32(out, op, 0)
buffer.writeu32(out, op + 4, 0)
buffer.writestring(out, op + 8, FOOTER)
op += 26
local res = buffer.create(op)
buffer.copy(res, 0, out, 0, op)
return res, nil
end
return Tga