image.codec\codec\tga_encode.mbt
92% · 46 / 50 points · 63 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # TGA 编码 TGA Encode - 3
/// - 4
/// TGA 图像格式编码 - 5
/// TGA 图像格式编码 TGA image format encoding - 6
// 纯 MoonBit TGA 编码(全目标可用:native/wasm/js) - 7
// 未压缩 true-color,top-down origin,BGR / BGRA - 8
- 9
///| - 10
/// TGA 编码(纯 MoonBit,全目标可用)。 - 11
/// - 12
/// 位深由通道数决定:1/2 通道 → 24-bit(灰度复制到 RGB),3 通道 → 24-bit,4 通道 → 32-bit BGRA。 - 13
/// 图像描述符按 TGA 规范写:bit5 = top-down origin;bit4(right-to-left)不置位; - 14
/// 低 4 位 = alpha 位深(32-bit 时 8,24-bit 时 0)。 - 15
pub fn encode_tga_pure(img : @types.Image) -> Bytes { - 16●
let width = img.width - 17
let height = img.height - 18
let channels = img.channels - 19
let data = img.data - 20●
let bpp = if channels >= 4 { 32 } else { 24 } - 21
let out : Array[Byte] = [] - 22
// TGA Header (18 bytes) - 23●
out.push(b'\x00') // id length - 24●
out.push(b'\x00') // color map type - 25●
out.push(b'\x02') // image type = uncompressed true-color - 26●
out.push(b'\x00') // color map spec (5) - 27●
out.push(b'\x00') - 28●
out.push(b'\x00') - 29●
out.push(b'\x00') - 30●
out.push(b'\x00') - 31●
out.push(b'\x00') // x origin (2) - 32●
out.push(b'\x00') - 33●
out.push(b'\x00') // y origin (2) - 34●
out.push(b'\x00') - 35●
out.push((width & 0xFF).to_byte()) - 36●
out.push(((width >> 8) & 0xFF).to_byte()) - 37●
out.push((height & 0xFF).to_byte()) - 38●
out.push(((height >> 8) & 0xFF).to_byte()) - 39●
out.push(bpp.to_byte()) - 40
// 描述符:bit5 = 1(top-down),低 4 位 = alpha 位深(32-bit 为 8) - 41●
out.push(if bpp == 32 { b'\x28' } else { b'\x20' }) - 42
// Pixel data (top-down, BGR(A)) - 43
// 无 raise 签名:像素缓冲区短于声明尺寸时按可用像素数截断写入,不越界 panic - 44◐
let ch = if channels < 1 { 1 } else { channels } - 45
let px_total = width * height - 46●
let avail_px = data.length() / ch - 47◐
let n_px = if avail_px < px_total { avail_px } else { px_total } - 48
let mut i = 0 - 49
while i < n_px { - 50●
let idx = i * ch - 51●
let r = data[idx].to_int() - 52◐
let g = if ch >= 2 { data[idx + 1].to_int() } else { r } - 53◐
let b = if ch >= 3 { data[idx + 2].to_int() } else { r } - 54●
out.push(b.to_byte()) - 55●
out.push(g.to_byte()) - 56●
out.push(r.to_byte()) - 57
if bpp == 32 { - 58●
out.push(data[idx + 3]) - 59
} - 60
i += 1 - 61
} - 62●
Bytes::from_array(out) - 63
}