image.codec\codec\pnm_extended.mbt

88.9% · 24 / 27 points · 77 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/// # PNM 扩展 PNM Extended
  3. 3///
  4. 4/// PNM 扩展功能 PNM extended features
  5. 5
  6. 6///|
  7. 7/// PNM 扩展信息(包含格式类型、maxval、位深等)
  8. 8pub struct PnmInfoExtended {
  9. 9 width : Int32
  10. 10 height : Int32
  11. 11 format_type : String
  12. 12 maxval : Int32
  13. 13 bit_depth : Int32
  14. 14 num_channels : Int32
  15. 15 has_alpha : Bool
  16. 16 is_binary : Bool
  17. 17}
  18. 18
  19. 19///|
  20. 20/// 检测数据是否为 PNM 格式(P1-P6)
  21. 21pub fn is_pnm_format(data : Bytes) -> Bool {
  22. 22● let len = data.length()
  23. 23 if len < 2 {
  24. 24● return false
  25. 25 }
  26. 26● data[0].to_int() == 0x50 &&
  27. 27● data[1].to_int() >= 0x31 &&
  28. 28● data[1].to_int() <= 0x36
  29. 29}
  30. 30
  31. 31///|
  32. 32/// 解析 PNM 扩展头部信息
  33. 33///
  34. 34/// 支持 P1(PBM)/P2(PGM ASCII)/P3(PPM ASCII)/P4(PBM binary)/P5(PGM binary)/P6(PPM binary)
  35. 35pub fn pnm_info_extended(
  36. 36 data : Bytes,
  37. 37) -> PnmInfoExtended raise @types.LoadError {
  38. 38● if !is_pnm_format(data) {
  39. 39● raise @types.LoadError::UnsupportedFormat("Not a PNM file")
  40. 40 }
  41. 41● let len = data.length()
  42. 42● let magic1 = data[1].to_int()
  43. 43● let format_type = "P" + (magic1 - 0x30).to_string()
  44. 44 let is_binary = magic1 >= 0x34
  45. 45● let num_channels = match magic1 {
  46. 46● 0x31 | 0x34 => 1 // PBM
  47. 47● 0x32 | 0x35 => 1 // PGM
  48. 48● 0x33 | 0x36 => 3 // PPM
  49. 49○ _ => 0
  50. 50 }
  51. 51 let pos = Ref(2)
  52. 52● pnm_skip_ws_and_comments(data, pos, len)
  53. 53● let width = pnm_read_ascii_int(data, pos, len)
  54. 54● pnm_skip_ws_and_comments(data, pos, len)
  55. 55● let height = pnm_read_ascii_int(data, pos, len)
  56. 56 // PBM (P1/P4) 没有 maxval,固定为 1
  57. 57 let maxval = if magic1 == 0x31 || magic1 == 0x34 {
  58. 58● 1
  59. 59 } else {
  60. 60● pnm_skip_ws_and_comments(data, pos, len)
  61. 61● pnm_read_ascii_int(data, pos, len)
  62. 62 }
  63. 63 if width == 0 || height == 0 {
  64. 64○ raise @types.LoadError::DecodeFailed("PNM 尺寸无效")
  65. 65 }
  66. 66◐ let bit_depth = if maxval < 256 { 8 } else { 16 }
  67. 67 PnmInfoExtended::{
  68. 68 width,
  69. 69 height,
  70. 70 format_type,
  71. 71 maxval,
  72. 72 bit_depth,
  73. 73 num_channels,
  74. 74 has_alpha: false,
  75. 75 is_binary,
  76. 76 }
  77. 77}