image.codec\codec\gif_extended.mbt

92.3% · 24 / 26 points · 81 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/// # GIF 扩展 GIF Extended
  3. 3///
  4. 4/// GIF 扩展功能 GIF extended features
  5. 5
  6. 6///|
  7. 7/// GIF 扩展信息(包含版本、全局颜色表、动画标志等)
  8. 8pub struct GifInfoExtended {
  9. 9 width : Int32
  10. 10 height : Int32
  11. 11 version : String
  12. 12 has_global_color_table : Bool
  13. 13 global_color_table_size : Int32
  14. 14 color_resolution : Int32
  15. 15 is_sorted : Bool
  16. 16 background_color_index : Int32
  17. 17 pixel_aspect_ratio : Int32
  18. 18 num_channels : Int32
  19. 19 has_alpha : Bool
  20. 20}
  21. 21
  22. 22///|
  23. 23/// 检测数据是否为 GIF 格式
  24. 24pub fn is_gif_format(data : Bytes) -> Bool {
  25. 25● let len = data.length()
  26. 26 if len < 6 {
  27. 27● return false
  28. 28 }
  29. 29 // "GIF87a" or "GIF89a"
  30. 30● data[0].to_int() == 0x47 &&
  31. 31● data[1].to_int() == 0x49 &&
  32. 32● data[2].to_int() == 0x46 &&
  33. 33● data[3].to_int() == 0x38 &&
  34. 34● data[5].to_int() == 0x61 &&
  35. 35● (data[4].to_int() == 0x37 || data[4].to_int() == 0x39)
  36. 36}
  37. 37
  38. 38///|
  39. 39/// 解析 GIF 扩展头部信息
  40. 40pub fn gif_info_extended(
  41. 41 data : Bytes,
  42. 42) -> GifInfoExtended raise @types.LoadError {
  43. 43● if !is_gif_format(data) {
  44. 44● raise @types.LoadError::UnsupportedFormat("Not a GIF file")
  45. 45 }
  46. 46● let len = data.length()
  47. 47 if len < 13 {
  48. 48○ raise @types.LoadError::DecodeFailed("GIF 数据过短")
  49. 49 }
  50. 50● let version = if data[4].to_int() == 0x37 { "87a" } else { "89a" }
  51. 51● let width = read_u16_le(data, 6)
  52. 52● let height = read_u16_le(data, 8)
  53. 53● let packed = data[10].to_int()
  54. 54 let has_global_color_table = (packed & 0x80) != 0
  55. 55 let color_resolution = ((packed >> 4) & 0x07) + 1
  56. 56 let is_sorted = (packed & 0x08) != 0
  57. 57 let gct_size_bits = packed & 0x07
  58. 58 let global_color_table_size = if has_global_color_table {
  59. 59● 1 << (gct_size_bits + 1)
  60. 60 } else {
  61. 61● 0
  62. 62 }
  63. 63● let background_color_index = data[11].to_int()
  64. 64● let pixel_aspect_ratio = data[12].to_int()
  65. 65 if width == 0 || height == 0 {
  66. 66○ raise @types.LoadError::DecodeFailed("GIF 尺寸无效")
  67. 67 }
  68. 68 GifInfoExtended::{
  69. 69 width,
  70. 70 height,
  71. 71 version,
  72. 72 has_global_color_table,
  73. 73 global_color_table_size,
  74. 74 color_resolution,
  75. 75 is_sorted,
  76. 76 background_color_index,
  77. 77 pixel_aspect_ratio,
  78. 78 num_channels: 3,
  79. 79 has_alpha: false,
  80. 80 }
  81. 81}