image.codec\codec\bmp_extended.mbt

66.7% · 24 / 36 points · 94 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/// # BMP 扩展 BMP Extended
  3. 3///
  4. 4/// BMP 扩展功能 BMP extended features
  5. 5
  6. 6///|
  7. 7/// BMP 扩展信息(包含位深、压缩方式、行序、调色板等)
  8. 8pub struct BmpInfoExtended {
  9. 9 width : Int32
  10. 10 height : Int32
  11. 11 bit_depth : Int32
  12. 12 num_channels : Int32
  13. 13 has_alpha : Bool
  14. 14 compression : Int32
  15. 15 compression_name : String
  16. 16 is_bottom_up : Bool
  17. 17 dib_size : Int32
  18. 18 num_colors : Int32
  19. 19 data_offset : Int32
  20. 20}
  21. 21
  22. 22///|
  23. 23/// 检测数据是否为 BMP 格式
  24. 24pub fn is_bmp_format(data : Bytes) -> Bool {
  25. 25● let len = data.length()
  26. 26 if len < 14 {
  27. 27● return false
  28. 28 }
  29. 29● data[0].to_int() == 0x42 && data[1].to_int() == 0x4D
  30. 30}
  31. 31
  32. 32///|
  33. 33fn bmp_compression_name(c : Int32) -> String {
  34. 34● match c {
  35. 35● 0 => "BI_RGB"
  36. 36○ 1 => "BI_RLE8"
  37. 37○ 2 => "BI_RLE4"
  38. 38○ 3 => "BI_BITFIELDS"
  39. 39○ 4 => "BI_JPEG"
  40. 40○ 5 => "BI_PNG"
  41. 41○ _ => "unknown"
  42. 42 }
  43. 43}
  44. 44
  45. 45///|
  46. 46/// 解析 BMP 扩展头部信息
  47. 47pub fn bmp_info_extended(
  48. 48 data : Bytes,
  49. 49) -> BmpInfoExtended raise @types.LoadError {
  50. 50● if !is_bmp_format(data) {
  51. 51● raise @types.LoadError::UnsupportedFormat("Not a BMP file")
  52. 52 }
  53. 53● let len = data.length()
  54. 54 if len < 54 {
  55. 55○ raise @types.LoadError::DecodeFailed("BMP 数据过短")
  56. 56 }
  57. 57● let data_offset = read_u32_le(data, 10)
  58. 58● let dib_size = read_u32_le(data, 14)
  59. 59● let width = read_u32_le(data, 18)
  60. 60● let height = read_u32_le(data, 22)
  61. 61● let bpp = read_u16_le(data, 28)
  62. 62● let compression = read_u32_le(data, 30)
  63. 63 let num_colors = if dib_size >= 40 && 46 < len {
  64. 64● let nc = read_u32_le(data, 46)
  65. 65 if nc > 0 {
  66. 66○ nc
  67. 67 } else {
  68. 68● 1 << bpp
  69. 69 }
  70. 70 } else {
  71. 71○ 0
  72. 72 }
  73. 73◐ let abs_width = if width < 0 { -width } else { width }
  74. 74◐ let abs_height = if height < 0 { -height } else { height }
  75. 75 if abs_width == 0 || abs_height == 0 {
  76. 76○ raise @types.LoadError::DecodeFailed("BMP 尺寸无效")
  77. 77 }
  78. 78 let is_bottom_up = height > 0
  79. 79 let has_alpha = bpp == 32
  80. 80 let num_channels = bpp / 8
  81. 81 BmpInfoExtended::{
  82. 82 width: abs_width,
  83. 83 height: abs_height,
  84. 84 bit_depth: bpp,
  85. 85 num_channels,
  86. 86 has_alpha,
  87. 87 compression,
  88. 88● compression_name: bmp_compression_name(compression),
  89. 89 is_bottom_up,
  90. 90 dib_size,
  91. 91 num_colors,
  92. 92 data_offset,
  93. 93 }
  94. 94}