image.codec\codec\tga_encode.mbt

92% · 46 / 50 points · 63 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

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