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 da8e4b17b7
commit 29fdc44b83
6 files changed
+629

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| 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` |
| image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
+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
+96
View File
@@ -0,0 +1,96 @@
-- image/tga tests: Pillow- and ImageMagick-written TGAs (RGB / RGBA / grey / grey + alpha / palette, raw and RLE, both
-- origins) and hand-written ones (15 / 16-bit pixels and colour maps, first index, right-to-left, RLE across rows, an
-- image ID) against the reference RGBA decodes; our encoder (raw / RLE, origins, 24 / 32-bit / grey) round-trips;
-- sniffing stays low without a footer; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/tga.py.
local T = require("@tests/T")
local Tga = require("@formats/image/tga")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/tga")
local t = T.suite("tga")
t:eq(Tga.name, "tga", "name")
t:check(Tga.caps.decode and Tga.caps.encode, "caps")
local function dec(data: any, opts: any?): (any, any)
return Tga.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts)
end
for _, c in Fx do
local img, err = dec(c.data)
t:check(img, c.name .. ": " .. tostring(err))
t:check(img.width == c.width and img.height == c.height, c.name .. ": size")
local worst, at = 0, -1
for i = 0, #c.rgba - 1 do
local d = math.abs(buffer.readu8(img.pixels, i) - string.byte(c.rgba, i + 1))
if d > worst then
worst, at = d, i
end
end
t:check(worst == 0, string.format("%s: differs from the reference by %d at byte %d", c.name, worst, at))
t:check(not img.meta.truncated, c.name .. ": not truncated")
-- round trips through our encoder
for _, rle in { false, true } do
for _, origin in { "bottom-left", "top-left" } do
local enc = Tga.encode(img, { rle = rle, origin = origin }) :: buffer
local back = dec(enc)
t:check(back and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), string.format("%s: round trip rle=%s %s", c.name, tostring(rle), origin))
end
end
end
t:note("%d files match the reference decodes and round-trip", #Fx)
do
local byName = {}
for _, c in Fx do
byName[c.name] = c
end
local id = dec(byName["hand-id-top"].data)
t:check(id.meta.text and id.meta.text.id == "hello", "image ID")
local g = dec(byName["pil-L-raw-top"].data, { native = true })
t:eq(g.format, "gray8", "native grey")
t:eq(Tga.encode(g) and buffer.readu8(Tga.encode(g) :: buffer, 2), 3, "gray8 encodes as type 3")
local rgb = dec(byName["pil-RGB-raw-top"].data, { native = true })
t:eq(rgb.format, "rgb8", "native rgb8")
local p = dec(byName["pil-P-raw-top"].data)
t:check(p.meta.palette and #p.meta.palette > 0, "palette in meta")
-- sniff: low without a footer, higher with ours, never for other formats
t:eq(Tga.sniff(Bytes.reader(buffer.fromstring(byName["hand-16bit"].data))), 0.2, "sniff without a footer")
t:eq(Tga.sniff(Bytes.reader(Tga.encode(p) :: buffer)), 0.9, "sniff with the footer")
t:eq(Tga.sniff(Bytes.reader(buffer.fromstring("\0\0\1\0\1\0\16\16\0\0\1\0\32\0\0\0\0\0\0\0\0\0"))), 0, "an ICO header is not a TGA")
t:eq(Tga.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n\0\0\0\13IHDR\0\0\0\0\0\0"))), 0, "a PNG is not a TGA")
-- encoder choices
local img = Types.Image.new(3, 2)
buffer.fill(img.pixels, 0, 255, 24)
t:eq(buffer.readu8(Tga.encode(img) :: buffer, 16), 24, "opaque rgba8 -> 24-bit")
buffer.writeu8(img.pixels, 3, 0)
t:eq(buffer.readu8(Tga.encode(img) :: buffer, 16), 32, "alpha -> 32-bit")
local _, e = Tga.encode(img, { origin = "middle" } :: any)
t:check(e and e.code == Err.ARG, "bad origin")
local _, e2 = Tga.encode(Types.Image.new(2, 2, "gray16"))
t:check(e2 and e2.code == Err.ARG, "gray16 refused")
-- truncation keeps what is there
local s = byName["pil-RGBA-raw-top"].data
local tr = dec(string.sub(s, 1, #s // 2))
t:check(tr and tr.meta.truncated, "truncated pixels flagged")
local _, e3 = dec(string.sub(s, 1, 10))
t:check(e3 and e3.code == Err.TRUNCATED, "short header")
local _, e4 = dec(s, { maxPixels = 10 })
t:check(e4 and e4.code == Err.LIMIT, "maxPixels")
end
do
local samples = {}
for i, c in Fx do
if i % 3 == 0 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Tga.decode(Bytes.reader(b))
end, samples)
end
t:done()
+87
View File
@@ -0,0 +1,87 @@
# TGA fixtures (tools/fixtures.py): files written by Pillow (RGB / RGBA / L / P / LA, raw and RLE, both origins) and
# ImageMagick (raw / RLE, palette, grey), plus hand-written ones (15 / 16-bit pixels and colour maps, 8 / 16-bit
# indexes with a first index, right-to-left, RLE packets crossing rows, an image ID, 16-bit grey + alpha);
# references = Pillow's RGBA decodes, ImageMagick's for the files Pillow
# refuses (right-to-left, 16-bit grey + alpha) and for 15 / 16-bit colour, where Pillow differs (5-bit scaling, alpha).
# tests/gen/tga.luau { { name, data, width, height, rgba (bytes) } }
import struct
CODE = r'''
import io, os, random, struct, subprocess, sys
from PIL import Image
magick = sys.argv[1]
rng = random.Random(9)
out = []
def emit(name, data, magick_ref=False):
try:
if magick_ref:
raise ValueError("15 / 16-bit: Pillow scales 5-bit values by x * 255 // 31 and inverts the alpha bit")
im = Image.open(io.BytesIO(data))
rgba = im.convert("RGBA").tobytes()
size = im.size
except Exception:
# files Pillow refuses (right-to-left, 16-bit grey + alpha): ImageMagick's decode
info = subprocess.run([magick, "tga:-", "-format", "%w %h", "info:"], input=data, capture_output=True, check=True).stdout.split()
size = (int(info[0]), int(info[1]))
rgba = subprocess.run([magick, "tga:-", "-depth", "8", "rgba:-"], input=data, capture_output=True, check=True).stdout
out.append((name, data, size, rgba))
w, h = 29, 17
px = bytearray()
for y in range(h):
for x in range(w):
a = 255 if (x + y) % 4 else (x * 37) % 256
px += bytes(((x * 9) % 256, (y * 15) % 256, rng.randrange(256) if x % 3 == 0 else 100, a))
rgba = Image.frombytes("RGBA", (w, h), bytes(px))
for mode in ("RGB", "RGBA", "L", "LA", "P"):
im = rgba.convert(mode) if mode != "P" else rgba.convert("RGB").quantize(37)
for comp in (None, "tga_rle"):
for orient in (1, -1):
b = io.BytesIO()
kw = {"orientation": orient}
if comp:
kw["compression"] = comp
im.save(b, "TGA", **kw)
emit("pil-%s-%s-%s" % (mode, comp or "raw", "top" if orient == 1 else "bottom"), b.getvalue())
# runs that cross rows (RLE)
flat = Image.new("RGB", (13, 9), (10, 20, 30))
for x in range(5):
flat.putpixel((x, 4), (200, 0, 0))
b = io.BytesIO(); flat.save(b, "TGA", compression="tga_rle"); emit("pil-runs", b.getvalue())
# ImageMagick writers
src = io.BytesIO(); rgba.save(src, "PNG")
for name, args in (("im-rgba", []), ("im-rle", ["-compress", "RLE"]), ("im-gray", ["-colorspace", "gray"]), ("im-palette", ["-colors", "20", "-type", "Palette"]),
("im-rgb", ["-alpha", "off"])):
r = subprocess.run([magick, "png:-"] + args + ["tga:-"], input=src.getvalue(), capture_output=True, check=True)
emit(name, r.stdout)
# hand-written
def hdr(idlen, cmt, it, cfirst, clen, cbits, w, h, depth, desc):
return struct.pack("<BBBHHBHHHHBB", idlen, cmt, it, cfirst, clen, cbits, 0, 0, w, h, depth, desc)
def p15(r, g, b, a=1):
return struct.pack("<H", (a << 15) | ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3))
cols = [((i * 40) % 256, (i * 90) % 256, (255 - i * 20) % 256) for i in range(12)]
w, h = 6, 4
idx = [(x + y * 2) % 12 for y in range(h) for x in range(w)]
emit("hand-16bit", hdr(0, 0, 2, 0, 0, 0, w, h, 16, 0) + b"".join(p15(*cols[i]) for i in idx), magick_ref=True)
emit("hand-15bit-rtl", hdr(0, 0, 2, 0, 0, 0, w, h, 15, 0x10) + b"".join(p15(*cols[i], a=0) for i in idx), magick_ref=True)
emit("hand-cmap16", hdr(0, 1, 1, 0, 12, 16, w, h, 8, 0x20) + b"".join(p15(*c) for c in cols) + bytes(idx), magick_ref=True)
emit("hand-cmap32-first", hdr(0, 1, 1, 4, 12, 32, w, h, 8, 0x28) + b"".join(bytes((c[2], c[1], c[0], 77)) for c in cols) + bytes(i + 4 for i in idx))
emit("hand-cmap24-rle", hdr(0, 1, 9, 0, 12, 24, w, h, 8, 0) + b"".join(bytes((c[2], c[1], c[0])) for c in cols) + bytes([0x80 + 9, 3, 0x05, 1, 2, 3, 4, 5, 6, 0x80 + 7, 11]))
emit("hand-id-top", hdr(5, 0, 3, 0, 0, 0, w, h, 8, 0x20) + b"hello" + bytes((i * 21) % 256 for i in idx))
emit("hand-graya16", hdr(0, 0, 3, 0, 0, 0, w, h, 16, 0x28) + b"".join(bytes(((i * 21) % 256, (i * 50) % 256)) for i in idx))
emit("hand-rle32-cross", hdr(0, 0, 10, 0, 0, 0, 5, 3, 32, 0x28) + bytes([0x80 + 6, 1, 2, 3, 200, 0x08]) + bytes(range(9 * 4)))
for name, data, size, rgba in out:
sys.stdout.buffer.write(struct.pack("<HIIII", len(name), len(data), size[0], size[1], len(rgba)) + name.encode() + data + rgba)
'''
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, w, h, rl = struct.unpack("<HIIII", raw[p:p + 18]); p += 18
name = raw[p:p + nl].decode(); p += nl
data = raw[p:p + dl]; p += dl
rgba = raw[p:p + rl]; p += rl
cases.append({"name": name, "data": data, "width": w, "height": h, "rgba": rgba})
ctx.emit("tga", cases)