image.codec\codec\tiff_codec.mbt

90.4% · 328 / 363 points · 901 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/// # TIFF 编解码 TIFF Codec
  3. 3///
  4. 4/// TIFF 图像格式编解码 TIFF image format encoding/decoding
  5. 5// 纯 MoonBit TIFF 编解码(全目标可用:native/wasm/js)
  6. 6// 支持无压缩 (Compression=1) 和 LZW 压缩 (Compression=5) TIFF
  7. 7// 支持 8-bit 灰度、8-bit RGB、8-bit RGBA
  8. 8// 规范: https://www.itu.int/rec/dologin.asp?lang=e&id=T-81-199303-I!!1-E
  9. 9
  10. 10///|
  11. 11/// TIFF IFD 条目
  12. 12priv struct TiffIfdEntry {
  13. 13 tag : Int32
  14. 14 type_id : Int32
  15. 15 count : Int32
  16. 16 value_or_offset : Int32
  17. 17}
  18. 18
  19. 19///|
  20. 20/// TIFF 解析上下文
  21. 21priv struct TiffContext {
  22. 22 data : Bytes
  23. 23 little_endian : Bool
  24. 24}
  25. 25
  26. 26///|
  27. 27/// 读取 16-bit 值(根据字节序)
  28. 28fn tiff_read_u16(ctx : TiffContext, offset : Int32) -> Int32 {
  29. 29● if ctx.little_endian {
  30. 30● read_u16_le(ctx.data, offset)
  31. 31 } else {
  32. 32● read_u16_be(ctx.data, offset)
  33. 33 }
  34. 34}
  35. 35
  36. 36///|
  37. 37/// 读取 32-bit 值(根据字节序)
  38. 38fn tiff_read_u32(ctx : TiffContext, offset : Int32) -> Int32 {
  39. 39● if ctx.little_endian {
  40. 40● read_u32_le(ctx.data, offset)
  41. 41 } else {
  42. 42● read_u32_be(ctx.data, offset)
  43. 43 }
  44. 44}
  45. 45
  46. 46///|
  47. 47/// 根据 type_id 和 count 计算 IFD 条目值的字节数
  48. 48fn tiff_type_size(type_id : Int32) -> Int32 {
  49. 49● match type_id {
  50. 50● 1 => 1 // BYTE
  51. 51● 2 => 1 // ASCII
  52. 52● 3 => 2 // SHORT
  53. 53● 4 => 4 // LONG
  54. 54● 5 => 8 // RATIONAL
  55. 55● 6 => 1 // SBYTE
  56. 56● 7 => 1 // UNDEFINED
  57. 57● 8 => 2 // SSHORT
  58. 58● 9 => 4 // SLONG
  59. 59● 10 => 8 // SRATIONAL
  60. 60● 11 => 4 // FLOAT
  61. 61● 12 => 8 // DOUBLE
  62. 62● _ => 0
  63. 63 }
  64. 64}
  65. 65
  66. 66///|
  67. 67/// 读取 IFD 条目的数值数组(当值超过 4 字节时从偏移处读取)
  68. 68fn tiff_read_values(ctx : TiffContext, entry : TiffIfdEntry) -> Array[Int32] {
  69. 69● let total_bytes = tiff_type_size(entry.type_id) * entry.count
  70. 70 let values : Array[Int32] = []
  71. 71 if total_bytes <= 4 {
  72. 72 // 值内联在 value_or_offset 中
  73. 73● let v = entry.value_or_offset
  74. 74● match entry.type_id {
  75. 75 1 | 7 =>
  76. 76● for i in 0..<entry.count {
  77. 77● values.push((v >> (i * 8)) & 0xFF)
  78. 78 }
  79. 79 3 =>
  80. 80● for i in 0..<entry.count {
  81. 81● values.push((v >> (i * 16)) & 0xFFFF)
  82. 82 }
  83. 83● 4 => values.push(v)
  84. 84 _ =>
  85. 85● for _ in 0..<entry.count {
  86. 86● values.push(0)
  87. 87 }
  88. 88 }
  89. 89 } else {
  90. 90 // 值在偏移处
  91. 91● let base = entry.value_or_offset
  92. 92● let len = ctx.data.length()
  93. 93● match entry.type_id {
  94. 94 1 | 7 =>
  95. 95● for i in 0..<entry.count {
  96. 96● if base + i < len {
  97. 97● values.push(ctx.data[base + i].to_int())
  98. 98 } else {
  99. 99● values.push(0)
  100. 100 }
  101. 101 }
  102. 102 3 =>
  103. 103● for i in 0..<entry.count {
  104. 104● values.push(tiff_read_u16(ctx, base + i * 2))
  105. 105 }
  106. 106 4 =>
  107. 107● for i in 0..<entry.count {
  108. 108● values.push(tiff_read_u32(ctx, base + i * 4))
  109. 109 }
  110. 110 _ =>
  111. 111● for _ in 0..<entry.count {
  112. 112● values.push(0)
  113. 113 }
  114. 114 }
  115. 115 }
  116. 116 values
  117. 117}
  118. 118
  119. 119///|
  120. 120/// 解析 IFD 条目
  121. 121fn tiff_parse_ifd(
  122. 122 ctx : TiffContext,
  123. 123 ifd_offset : Int32,
  124. 124) -> Array[TiffIfdEntry] raise @types.LoadError {
  125. 125● let len = ctx.data.length()
  126. 126 if ifd_offset + 2 > len {
  127. 127○ raise @types.LoadError::DecodeFailed("TIFF IFD 偏移越界")
  128. 128 }
  129. 129● let count = tiff_read_u16(ctx, ifd_offset)
  130. 130 if ifd_offset + 2 + count * 12 > len {
  131. 131○ raise @types.LoadError::DecodeFailed("TIFF IFD 条目数据不完整")
  132. 132 }
  133. 133 let entries : Array[TiffIfdEntry] = []
  134. 134 for i in 0..<count {
  135. 135● let base = ifd_offset + 2 + i * 12
  136. 136● let tag = tiff_read_u16(ctx, base)
  137. 137● let type_id = tiff_read_u16(ctx, base + 2)
  138. 138● let cnt = tiff_read_u32(ctx, base + 4)
  139. 139● let val_or_off = tiff_read_u32(ctx, base + 8)
  140. 140● entries.push(TiffIfdEntry::{
  141. 141 tag,
  142. 142 type_id,
  143. 143 count: cnt,
  144. 144 value_or_offset: val_or_off,
  145. 145 })
  146. 146 }
  147. 147 entries
  148. 148}
  149. 149
  150. 150///|
  151. 151/// 在 IFD 条目中查找指定 tag 的值数组
  152. 152fn tiff_get_values(
  153. 153 entries : Array[TiffIfdEntry],
  154. 154 ctx : TiffContext,
  155. 155 tag : Int32,
  156. 156) -> Array[Int32]? {
  157. 157● for i in 0..<entries.length() {
  158. 158● if entries[i].tag == tag {
  159. 159● return Some(tiff_read_values(ctx, entries[i]))
  160. 160 }
  161. 161 }
  162. 162 None
  163. 163}
  164. 164
  165. 165///|
  166. 166/// 在 IFD 条目中查找指定 tag 的单个值
  167. 167fn tiff_get_value(
  168. 168 entries : Array[TiffIfdEntry],
  169. 169 ctx : TiffContext,
  170. 170 tag : Int32,
  171. 171) -> Int32? {
  172. 172● match tiff_get_values(entries, ctx, tag) {
  173. 173● Some(arr) => if arr.length() > 0 { Some(arr[0]) } else { None }
  174. 174● None => None
  175. 175 }
  176. 176}
  177. 177
  178. 178// ==================== LZW 解码器 ====================
  179. 179
  180. 180///|
  181. 181/// 解码 TIFF LZW 压缩的字节流
  182. 182pub fn tiff_lzw_decode(data : Bytes) -> Array[Byte] raise @types.LoadError {
  183. 183● let len = data.length()
  184. 184 if len < 2 {
  185. 185● raise @types.LoadError::DecodeFailed("TIFF LZW 数据过短")
  186. 186 }
  187. 187● let init_code_len = data[0].to_int()
  188. 188 if init_code_len < 2 || init_code_len > 11 {
  189. 189● raise @types.LoadError::DecodeFailed("TIFF LZW 初始码长无效")
  190. 190 }
  191. 191 let clear_code = 1 << init_code_len
  192. 192 let eoi_code = clear_code + 1
  193. 193● let dict : Array[Int32] = Array::make(512, 0)
  194. 194 for i in 0..<=255 {
  195. 195● dict[i] = i
  196. 196 }
  197. 197 let mut next_code = clear_code + 2
  198. 198 let mut bit_pos = 8
  199. 199● let data_len = data.length()
  200. 200
  201. 201 fn read_bits(
  202. 202 data : Bytes,
  203. 203 pos : Int32,
  204. 204 count : Int32,
  205. 205 len : Int32,
  206. 206 ) -> (Int32, Int32) {
  207. 207● let mut code : Int32 = 0
  208. 208 let mut p = pos
  209. 209 let mut i : Int32 = 0
  210. 210 while i < count && p < len * 8 {
  211. 211● let byte_idx = p / 8
  212. 212 let bit_offset = p % 8
  213. 213 if byte_idx < len {
  214. 214● let bit = (data[byte_idx].to_int() >> bit_offset) & 1
  215. 215 code = code | (bit << i)
  216. 216 }
  217. 217 p += 1
  218. 218 i += 1
  219. 219 }
  220. 220 (code, p)
  221. 221 }
  222. 222
  223. 223 // 读取 CLEAR 码并推进 bit_pos
  224. 224● let (code, new_bit_pos) = read_bits(data, 8, init_code_len + 1, data_len)
  225. 225 bit_pos = new_bit_pos
  226. 226 if code != clear_code {
  227. 227● raise @types.LoadError::DecodeFailed("TIFF LZW 首码应为 CLEAR")
  228. 228 }
  229. 229
  230. 230 let output : Array[Byte] = []
  231. 231 let mut prev_code : Int32 = 0
  232. 232 let mut code_len = init_code_len
  233. 233 let mut done = false
  234. 234
  235. 235 while !done {
  236. 236● let (c, new_pos) = read_bits(data, bit_pos, code_len + 1, data_len)
  237. 237 bit_pos = new_pos
  238. 238
  239. 239 if c == eoi_code {
  240. 240● done = true
  241. 241● } else if c == clear_code {
  242. 242● for j in 0..<=255 {
  243. 243● dict[j] = j
  244. 244 }
  245. 245 next_code = clear_code + 2
  246. 246 code_len = init_code_len
  247. 247● } else if c < next_code {
  248. 248 // 输出 c 对应的字符串
  249. 249● if c <= 255 {
  250. 250● output.push(c.to_byte())
  251. 251 } else {
  252. 252 // 回溯字典获取字符串
  253. 253● let k = c
  254. 254 let path : Array[Int32] = [k]
  255. 255 let mut current = dict[k]
  256. 256 while current >= clear_code &&
  257. 257 current < next_code &&
  258. 258○ path.length() < 512 {
  259. 259○ path.push(current)
  260. 260 current = dict[current]
  261. 261 }
  262. 262 // 手动反转输出
  263. 263● let mut i = path.length()
  264. 264 while i > 0 {
  265. 265● i -= 1
  266. 266● output.push(path[i].to_byte())
  267. 267 }
  268. 268 if current <= 255 {
  269. 269● output.push(current.to_byte())
  270. 270 }
  271. 271 }
  272. 272 // 更新字典
  273. 273 if next_code < 4096 {
  274. 274● dict[next_code] = prev_code
  275. 275 next_code += 1
  276. 276 }
  277. 277 prev_code = c
  278. 278 } else {
  279. 279● raise @types.LoadError::DecodeFailed("TIFF LZW 码越界")
  280. 280 }
  281. 281 }
  282. 282 output
  283. 283}
  284. 284
  285. 285///|
  286. 286/// 解码 TIFF PackBits 压缩的字节流
  287. 287pub fn tiff_packbits_decode(data : Bytes) -> Array[Byte] raise @types.LoadError {
  288. 288● let len = data.length()
  289. 289 let mut pos : Int32 = 0
  290. 290 let output : Array[Byte] = []
  291. 291
  292. 292 while pos < len {
  293. 293● let count = data[pos].to_int()
  294. 294 pos += 1
  295. 295● let signed_count : Int32 = if count > 127 { count - 256 } else { count }
  296. 296
  297. 297 if signed_count == -128 {
  298. 298 // Extended PackBits
  299. 299● if pos + 1 >= len {
  300. 300● raise @types.LoadError::DecodeFailed(
  301. 301 "TIFF PackBits 扩展模式数据不足",
  302. 302 )
  303. 303 }
  304. 304● let extended_count = ((data[pos].to_int() << 8) | data[pos + 1].to_int()) -
  305. 305 32768
  306. 306 pos += 2
  307. 307 if extended_count >= 0 {
  308. 308 // 复制 extended_count + 1 个字节
  309. 309● let n = extended_count + 1
  310. 310 let mut i = 0
  311. 311 while i < n && pos < len {
  312. 312● output.push(data[pos])
  313. 313 pos += 1
  314. 314 i += 1
  315. 315 }
  316. 316 } else {
  317. 317 // 重复下一个字节
  318. 318● if pos >= len {
  319. 319○ raise @types.LoadError::DecodeFailed(
  320. 320 "TIFF PackBits 扩展模式数据不足",
  321. 321 )
  322. 322 }
  323. 323 let repeat_byte = data[pos]
  324. 324 pos += 1
  325. 325 let n = -extended_count + 1
  326. 326 let mut i = 0
  327. 327 while i < n {
  328. 328● output.push(repeat_byte)
  329. 329 i += 1
  330. 330 }
  331. 331 }
  332. 332● } else if signed_count >= 0 {
  333. 333 // 复制 count + 1 个字节
  334. 334● let n = signed_count + 1
  335. 335 let mut i = 0
  336. 336 while i < n && pos < len {
  337. 337● output.push(data[pos])
  338. 338 pos += 1
  339. 339 i += 1
  340. 340 }
  341. 341 } else {
  342. 342 // 重复下一个字节 (-signed_count + 1) 次
  343. 343● let repeat_count = -signed_count + 1
  344. 344 if pos >= len {
  345. 345○ raise @types.LoadError::DecodeFailed("TIFF PackBits 数据不足")
  346. 346 }
  347. 347 let repeat_byte = data[pos]
  348. 348 pos += 1
  349. 349 let mut i = 0
  350. 350 while i < repeat_count {
  351. 351● output.push(repeat_byte)
  352. 352 i += 1
  353. 353 }
  354. 354 }
  355. 355 }
  356. 356 output
  357. 357}
  358. 358
  359. 359///|
  360. 360/// 解码 TIFF 字节流为 Image,支持无压缩 (Compression=1) 和 LZW 压缩 (Compression=5) 8-bit 灰度/RGB/RGBA Decode TIFF byte stream to Image, Supports uncompressed (Compression=1) and LZW compressed (Compression=5) 8-bit grayscale/RGB/RGBA
  361. 361
  362. 362///|
  363. 363/// 参数 Parameters:
  364. 364/// - `data` - TIFF 字节流 TIFF byte stream
  365. 365///
  366. 366/// 返回 Return:
  367. 367/// - 解码后的 8-bit Image Decoded 8-bit Image
  368. 368///
  369. 369/// 错误 Errors:
  370. 370/// - `LoadError::DecodeFailed` - 数据过短、TIFF 签名无效、不支持的压缩/格式 Data too short, invalid TIFF signature, unsupported compression/format
  371. 371pub fn decode_tiff_pure(data : Bytes) -> @types.Image raise @types.LoadError {
  372. 372● let len = data.length()
  373. 373 if len < 8 {
  374. 374● raise @types.LoadError::DecodeFailed("TIFF 数据过短")
  375. 375 }
  376. 376 // 检查字节序
  377. 377● let little_endian = match data[0].to_int() {
  378. 378● 0x49 => true // 'I' = little-endian
  379. 379● 0x4D => false // 'M' = big-endian
  380. 380● _ => raise @types.LoadError::DecodeFailed("TIFF 字节序标记无效")
  381. 381 }
  382. 382 let ctx = TiffContext::{ data, little_endian, }
  383. 383 // 检查 magic 42
  384. 384● let magic = tiff_read_u16(ctx, 2)
  385. 385 if magic != 42 {
  386. 386● raise @types.LoadError::DecodeFailed("TIFF magic 无效")
  387. 387 }
  388. 388● let ifd_offset = tiff_read_u32(ctx, 4)
  389. 389 if ifd_offset < 0 || ifd_offset >= len {
  390. 390● raise @types.LoadError::DecodeFailed("TIFF IFD 偏移无效")
  391. 391 }
  392. 392● let entries = tiff_parse_ifd(ctx, ifd_offset)
  393. 393 // 读取必要字段
  394. 394● let width = match tiff_get_value(entries, ctx, 256) {
  395. 395● Some(w) => w
  396. 396● None => raise @types.LoadError::DecodeFailed("TIFF 缺少 ImageWidth")
  397. 397 }
  398. 398● let height = match tiff_get_value(entries, ctx, 257) {
  399. 399● Some(h) => h
  400. 400○ None => raise @types.LoadError::DecodeFailed("TIFF 缺少 ImageLength")
  401. 401 }
  402. 402● let bits_per_sample = match tiff_get_values(entries, ctx, 258) {
  403. 403● Some(arr) => arr
  404. 404● None => [8]
  405. 405 }
  406. 406● let compression = match tiff_get_value(entries, ctx, 259) {
  407. 407● Some(c) => c
  408. 408● None => 1
  409. 409 }
  410. 410● let photometric = match tiff_get_value(entries, ctx, 262) {
  411. 411● Some(p) => p
  412. 412● None => 1
  413. 413 }
  414. 414● let samples_per_pixel = match tiff_get_value(entries, ctx, 277) {
  415. 415● Some(s) => s
  416. 416● None => 1
  417. 417 }
  418. 418● let strip_offsets = match tiff_get_values(entries, ctx, 273) {
  419. 419● Some(arr) => arr
  420. 420● None => raise @types.LoadError::DecodeFailed("TIFF 缺少 StripOffsets")
  421. 421 }
  422. 422● let rows_per_strip = match tiff_get_value(entries, ctx, 278) {
  423. 423● Some(r) => r
  424. 424● None => height
  425. 425 }
  426. 426● let strip_byte_counts = match tiff_get_values(entries, ctx, 279) {
  427. 427● Some(arr) => arr
  428. 428● None => []
  429. 429 }
  430. 430 // CCITT 1D(Compression=2 / 3):1-bit、单通道,必须在 8-bit 门槛之前单独分支
  431. 431 if compression == 2 || compression == 3 {
  432. 432● if samples_per_pixel != 1 {
  433. 433○ raise @types.LoadError::DecodeFailed("TIFF CCITT 仅支持单通道")
  434. 434 }
  435. 435● if bits_per_sample.length() != 1 || bits_per_sample[0] != 1 {
  436. 436● raise @types.LoadError::DecodeFailed("TIFF CCITT 需要 1-bit 样本")
  437. 437 }
  438. 438● let t4_options = match tiff_get_value(entries, ctx, 292) {
  439. 439● Some(o) => o
  440. 440● None => 0
  441. 441 }
  442. 442 // T4Options bit0 置位 = 混合 2D 行,本实现只做 1D
  443. 443 if compression == 3 && (t4_options & 1) != 0 {
  444. 444● raise @types.LoadError::DecodeFailed(
  445. 445 "TIFF Group 3 的 2D 行(T4Options bit0)不支持",
  446. 446 )
  447. 447 }
  448. 448 if width <= 0 || height <= 0 {
  449. 449○ raise @types.LoadError::DecodeFailed("TIFF 尺寸无效")
  450. 450 }
  451. 451● @types.check_dims(width, height, 1)
  452. 452 let has_eol = compression == 3
  453. 453 let _ = photometric
  454. 454● let pixels : Array[Byte] = Array::make(width * height, b'\xFF')
  455. 455 let mut row : Int32 = 0
  456. 456 let mut si : Int32 = 0
  457. 457● while si < strip_offsets.length() && row < height {
  458. 458● let off = strip_offsets[si]
  459. 459● let cnt = if si < strip_byte_counts.length() {
  460. 460● strip_byte_counts[si]
  461. 461 } else {
  462. 462○ len - off
  463. 463 }
  464. 464 let rows_in_strip = if row + rows_per_strip > height {
  465. 465○ height - row
  466. 466 } else {
  467. 467● rows_per_strip
  468. 468 }
  469. 469 let tmp : Array[Byte] = []
  470. 470 let mut i = off
  471. 471 let end = off + cnt
  472. 472 while i < end && i < len {
  473. 473● tmp.push(ctx.data[i])
  474. 474 i += 1
  475. 475 }
  476. 476● let bits = ccitt_decode_strip(
  477. 477● Bytes::from_array(tmp),
  478. 478 width,
  479. 479 rows_in_strip,
  480. 480 has_eol,
  481. 481 )
  482. 482 // 传真编码器按「样本位值」出码:白游程 = 位 0、黑游程 = 位 1;
  483. 483 // 再由 Photometric 决定位值到亮度的方向(1 = BlackIsZero 时 0 是黑)
  484. 484 let white_is_zero = photometric == 0
  485. 485 for k in 0..<(width * rows_in_strip) {
  486. 486● let is_black = bits[k]
  487. 487● let v = if is_black == white_is_zero { b'\x00' } else { b'\xFF' }
  488. 488 pixels[row * width + k] = v
  489. 489 }
  490. 490 row += rows_in_strip
  491. 491 si += 1
  492. 492 }
  493. 493 return @types.Image::{
  494. 494 width,
  495. 495 height,
  496. 496 channels: 1,
  497. 497● data: Bytes::from_array(pixels),
  498. 498 }
  499. 499 }
  500. 500 // 支持无压缩、LZW、PackBits 和 Deflate 压缩
  501. 501 if compression != 1 &&
  502. 502 compression != 5 &&
  503. 503 compression != 32773 &&
  504. 504 compression != 8 {
  505. 505● raise @types.LoadError::DecodeFailed(
  506. 506 "TIFF 仅支持无压缩 (1)、CCITT 1D (2)、Group 3 (3)、LZW (5)、PackBits (32773) 和 Deflate (8)",
  507. 507 )
  508. 508 }
  509. 509 // 仅支持 8-bit
  510. 510● for i in 0..<bits_per_sample.length() {
  511. 511● if bits_per_sample[i] != 8 {
  512. 512● raise @types.LoadError::DecodeFailed("TIFF 仅支持 8-bit 样本")
  513. 513 }
  514. 514 }
  515. 515 if width <= 0 || height <= 0 {
  516. 516● raise @types.LoadError::DecodeFailed("TIFF 尺寸无效")
  517. 517 }
  518. 518 // 确定输出 channels
  519. 519 let out_channels = samples_per_pixel
  520. 520 if out_channels != 1 && out_channels != 3 && out_channels != 4 {
  521. 521● raise @types.LoadError::DecodeFailed(
  522. 522 "TIFF 仅支持 1/3/4 samples per pixel",
  523. 523 )
  524. 524 }
  525. 525● @types.check_dims(width, height, out_channels)
  526. 526 // 读取像素数据(支持 LZW/PackBits 解压)
  527. 527 let pixel_count = width * height
  528. 528● let pixels : Array[Byte] = Array::make(pixel_count * out_channels, b'\x00')
  529. 529 let bytes_per_pixel = out_channels
  530. 530 // 如果使用了压缩,先解压所有 strip 数据
  531. 531 let decompressed : Bytes = if compression == 5 {
  532. 532 // LZW 解压:逐 strip 读取并解码
  533. 533● let all_data : Array[Byte] = []
  534. 534 let mut strip_idx : Int32 = 0
  535. 535● while strip_idx < strip_offsets.length() {
  536. 536● let strip_offset = strip_offsets[strip_idx]
  537. 537● let byte_count = if strip_idx < strip_byte_counts.length() {
  538. 538● strip_byte_counts[strip_idx]
  539. 539 } else {
  540. 540○ width * height * out_channels - all_data.length()
  541. 541 }
  542. 542 // 手动提取 strip 数据(Bytes 无 slice 方法,逐字节取)
  543. 543 let strip_data : Bytes = {
  544. 544 let tmp : Array[Byte] = []
  545. 545 let mut i = strip_offset
  546. 546 let end = i + byte_count
  547. 547 while i < end {
  548. 548● if i < len {
  549. 549● tmp.push(ctx.data[i])
  550. 550 }
  551. 551 i += 1
  552. 552 }
  553. 553● Bytes::from_array(tmp)
  554. 554 }
  555. 555● let decoded = tiff_lzw_decode(strip_data)
  556. 556 // 手动拼接(Array 无 concat 方法,逐元素 push)
  557. 557 for d in decoded {
  558. 558● all_data.push(d)
  559. 559 }
  560. 560 strip_idx += 1
  561. 561 }
  562. 562● Bytes::from_array(all_data)
  563. 563● } else if compression == 32773 {
  564. 564 // PackBits 解压:逐 strip 读取并解码
  565. 565● let all_data : Array[Byte] = []
  566. 566 let mut strip_idx : Int32 = 0
  567. 567● while strip_idx < strip_offsets.length() {
  568. 568● let strip_offset = strip_offsets[strip_idx]
  569. 569● let byte_count = if strip_idx < strip_byte_counts.length() {
  570. 570● strip_byte_counts[strip_idx]
  571. 571 } else {
  572. 572○ width * height * out_channels - all_data.length()
  573. 573 }
  574. 574 // 手动提取 strip 数据
  575. 575 let strip_data : Bytes = {
  576. 576 let tmp : Array[Byte] = []
  577. 577 let mut i = strip_offset
  578. 578 let end = i + byte_count
  579. 579 while i < end {
  580. 580● if i < len {
  581. 581● tmp.push(ctx.data[i])
  582. 582 }
  583. 583 i += 1
  584. 584 }
  585. 585● Bytes::from_array(tmp)
  586. 586 }
  587. 587● let decoded = tiff_packbits_decode(strip_data)
  588. 588 for d in decoded {
  589. 589● all_data.push(d)
  590. 590 }
  591. 591 strip_idx += 1
  592. 592 }
  593. 593● Bytes::from_array(all_data)
  594. 594● } else if compression == 8 {
  595. 595 // Deflate 解压:逐 strip 读取并解码
  596. 596○ let all_data : Array[Byte] = []
  597. 597 let mut strip_idx : Int32 = 0
  598. 598○ while strip_idx < strip_offsets.length() {
  599. 599○ let strip_offset = strip_offsets[strip_idx]
  600. 600○ let byte_count = if strip_idx < strip_byte_counts.length() {
  601. 601○ strip_byte_counts[strip_idx]
  602. 602 } else {
  603. 603○ width * height * out_channels - all_data.length()
  604. 604 }
  605. 605 // 手动提取 strip 数据
  606. 606 let strip_data : Bytes = {
  607. 607 let tmp : Array[Byte] = []
  608. 608 let mut i = strip_offset
  609. 609 let end = i + byte_count
  610. 610 while i < end {
  611. 611○ if i < len {
  612. 612○ tmp.push(ctx.data[i])
  613. 613 }
  614. 614 i += 1
  615. 615 }
  616. 616○ Bytes::from_array(tmp)
  617. 617 }
  618. 618○ let decoded = tiff_deflate_decode(strip_data)
  619. 619 for d in decoded {
  620. 620○ all_data.push(d)
  621. 621 }
  622. 622 strip_idx += 1
  623. 623 }
  624. 624○ Bytes::from_array(all_data)
  625. 625 } else {
  626. 626 // 无压缩:直接从 strip offset 读取像素数据
  627. 627● let all_data : Array[Byte] = []
  628. 628 let mut strip_idx : Int32 = 0
  629. 629● while strip_idx < strip_offsets.length() {
  630. 630● let strip_offset = strip_offsets[strip_idx]
  631. 631● let byte_count = if strip_idx < strip_byte_counts.length() {
  632. 632● strip_byte_counts[strip_idx]
  633. 633 } else {
  634. 634● width * height * out_channels - all_data.length()
  635. 635 }
  636. 636 let mut i = strip_offset
  637. 637 let end = i + byte_count
  638. 638 while i < end && i < len {
  639. 639● all_data.push(ctx.data[i])
  640. 640 i += 1
  641. 641 }
  642. 642 strip_idx += 1
  643. 643 }
  644. 644● Bytes::from_array(all_data)
  645. 645 }
  646. 646● let len = decompressed.length()
  647. 647 let mut row = 0
  648. 648● for _ in 0..<strip_offsets.length() {
  649. 649● if row >= height {
  650. 650○ break
  651. 651 }
  652. 652 let rows_in_strip = if row + rows_per_strip > height {
  653. 653○ height - row
  654. 654 } else {
  655. 655● rows_per_strip
  656. 656 }
  657. 657 for r in 0..<rows_in_strip {
  658. 658● let y = row + r
  659. 659 let row_start = r * width * bytes_per_pixel
  660. 660 for x in 0..<width {
  661. 661● let src = row_start + x * bytes_per_pixel
  662. 662 let dst = (y * width + x) * out_channels
  663. 663 if src + bytes_per_pixel > len {
  664. 664● raise @types.LoadError::DecodeFailed("TIFF 像素数据越界")
  665. 665 }
  666. 666 if out_channels == 1 {
  667. 667 // 灰度
  668. 668● let g = decompressed[src].to_int()
  669. 669◐ let val = if photometric == 0 { 255 - g } else { g }
  670. 670● pixels[dst] = val.to_byte()
  671. 671 // RGB 或 RGBA
  672. 672● } else if photometric == 2 {
  673. 673 // RGB
  674. 674● pixels[dst] = decompressed[src]
  675. 675 pixels[dst + 1] = decompressed[src + 1]
  676. 676 pixels[dst + 2] = decompressed[src + 2]
  677. 677 if out_channels == 4 {
  678. 678● pixels[dst + 3] = decompressed[src + 3]
  679. 679 }
  680. 680● } else if photometric == 0 || photometric == 1 {
  681. 681 // 灰度存储为多通道(不常见,但处理之)
  682. 682● let g = decompressed[src].to_int()
  683. 683● let val = if photometric == 0 { 255 - g } else { g }
  684. 684● pixels[dst] = val.to_byte()
  685. 685● pixels[dst + 1] = val.to_byte()
  686. 686● pixels[dst + 2] = val.to_byte()
  687. 687 if out_channels == 4 {
  688. 688● pixels[dst + 3] = decompressed[src + 3]
  689. 689 }
  690. 690 } else {
  691. 691○ raise @types.LoadError::DecodeFailed(
  692. 692 "TIFF 不支持的 PhotometricInterpretation",
  693. 693 )
  694. 694 }
  695. 695 }
  696. 696 }
  697. 697 row += rows_in_strip
  698. 698 }
  699. 699 @types.Image::{
  700. 700 width,
  701. 701 height,
  702. 702 channels: out_channels,
  703. 703● data: Bytes::from_array(pixels),
  704. 704 }
  705. 705}
  706. 706
  707. 707///|
  708. 708/// 将 Image 编码为无压缩 TIFF 字节流(小端序),支持 1/3/4 channels Encode Image to uncompressed TIFF byte stream (little-endian), Supports 1/3/4 channels
  709. 709
  710. 710///|
  711. 711/// 参数 Parameters:
  712. 712/// - `img` - 输入图像 Input image
  713. 713///
  714. 714/// 返回 Return:
  715. 715/// - TIFF 字节流 TIFF byte stream
  716. 716///
  717. 717/// 错误 Errors:
  718. 718/// - `LoadError::EncodeFailed` - channels 不为 1/3/4 Channels not 1/3/4
  719. 719pub fn encode_tiff_pure(img : @types.Image) -> Bytes raise @types.LoadError {
  720. 720● let width = img.width
  721. 721 let height = img.height
  722. 722 let channels = img.channels
  723. 723 let data = img.data
  724. 724 if channels != 1 && channels != 3 && channels != 4 {
  725. 725● raise @types.LoadError::EncodeFailed(
  726. 726 "TIFF 编码需要 channels 为 1 (灰度)、3 (RGB) 或 4 (RGBA)",
  727. 727 )
  728. 728 }
  729. 729 if width <= 0 || height <= 0 {
  730. 730● raise @types.LoadError::EncodeFailed("TIFF 编码需要宽高大于 0")
  731. 731 }
  732. 732 // 像素缓冲区必须正好覆盖 width*height*channels:少一个字节时下面的索引会越界 panic
  733. 733 // (历史上这里直接 trap 0xC0000409,属"用户数据即可触发"的崩溃,S22 改为结构化错误)
  734. 734 let expected_size = width * height * channels
  735. 735● if data.length() != expected_size {
  736. 736● raise @types.LoadError::EncodeFailed(
  737. 737 "TIFF 编码像素数据长度不匹配:期望 \{expected_size},实际 \{data.length()}",
  738. 738 )
  739. 739 }
  740. 740 let out : Array[Byte] = []
  741. 741 // TIFF Header (8 bytes)
  742. 742● out.push(b'\x49') // 'I' little-endian
  743. 743● out.push(b'\x49') // 'I'
  744. 744● write_u16_le(out, 42) // magic
  745. 745● write_u32_le(out, 8) // IFD offset (immediately after header)
  746. 746 // IFD: count(2) + entries(12 each) + next IFD offset(4)
  747. 747 // 需要的 tags:
  748. 748 // 256 ImageWidth, 257 ImageLength, 258 BitsPerSample,
  749. 749 // 259 Compression, 262 Photometric, 273 StripOffsets,
  750. 750 // 277 SamplesPerPixel, 278 RowsPerStrip, 279 StripByteCounts
  751. 751 let num_entries = 9
  752. 752 let ifd_size = 2 + num_entries * 12 + 4
  753. 753 // BitsPerSample 可能需要外部存储(如果 channels > 1,3个SHORT=6字节 > 4字节)
  754. 754 let bps_offset = 8 + ifd_size
  755. 755 let bps_external = channels > 1
  756. 756● let bps_bytes = if bps_external { 6 } else { 0 } // 3 SHORTs for RGB, 4 SHORTs for RGBA
  757. 757● let bps_actual = if channels == 4 { 8 } else { bps_bytes }
  758. 758 // 像素数据偏移
  759. 759 let pixel_offset = bps_offset + bps_actual
  760. 760 let pixel_size = width * height * channels
  761. 761 // 写入 IFD
  762. 762● write_u16_le(out, num_entries)
  763. 763 // 辅助函数:写入 IFD 条目
  764. 764 let write_entry = fn(
  765. 765 tag : Int32,
  766. 766 type_id : Int32,
  767. 767 count : Int32,
  768. 768 value : Int32,
  769. 769 ) -> Unit {
  770. 770● write_u16_le(out, tag)
  771. 771● write_u16_le(out, type_id)
  772. 772● write_u32_le(out, count)
  773. 773● write_u32_le(out, value)
  774. 774 }
  775. 775 // 256: ImageWidth (LONG)
  776. 776● write_entry(256, 4, 1, width)
  777. 777 // 257: ImageLength (LONG)
  778. 778● write_entry(257, 4, 1, height)
  779. 779 // 258: BitsPerSample (SHORT)
  780. 780 if bps_external {
  781. 781 // 值在外部存储
  782. 782● write_entry(258, 3, channels, bps_offset)
  783. 783 } else {
  784. 784 // 单通道,值内联
  785. 785● write_entry(258, 3, 1, 8)
  786. 786 }
  787. 787 // 259: Compression (SHORT) = 1 (无压缩)
  788. 788● write_entry(259, 3, 1, 1)
  789. 789 // 262: PhotometricInterpretation (SHORT)
  790. 790● let photometric = if channels == 1 { 1 } else { 2 } // 1=BlackIsZero, 2=RGB
  791. 791● write_entry(262, 3, 1, photometric)
  792. 792 // 273: StripOffsets (LONG)
  793. 793● write_entry(273, 4, 1, pixel_offset)
  794. 794 // 277: SamplesPerPixel (SHORT)
  795. 795● write_entry(277, 3, 1, channels)
  796. 796 // 278: RowsPerStrip (LONG)
  797. 797● write_entry(278, 4, 1, height)
  798. 798 // 279: StripByteCounts (LONG)
  799. 799● write_entry(279, 4, 1, pixel_size)
  800. 800 // Next IFD offset = 0 (无更多 IFD)
  801. 801● write_u32_le(out, 0)
  802. 802 // BitsPerSample 外部数据
  803. 803 if bps_external {
  804. 804● for _ in 0..<channels {
  805. 805● write_u16_le(out, 8)
  806. 806 }
  807. 807 }
  808. 808 // 像素数据
  809. 809 for y in 0..<height {
  810. 810● for x in 0..<width {
  811. 811● let idx = (y * width + x) * channels
  812. 812 if channels == 1 {
  813. 813● out.push(data[idx])
  814. 814 } else {
  815. 815 // RGB 或 RGBA,TIFF 存储为 RGB(A)
  816. 816● out.push(data[idx])
  817. 817● out.push(data[idx + 1])
  818. 818● out.push(data[idx + 2])
  819. 819 if channels == 4 {
  820. 820● out.push(data[idx + 3])
  821. 821 }
  822. 822 }
  823. 823 }
  824. 824 }
  825. 825● Bytes::from_array(out)
  826. 826}
  827. 827
  828. 828///|
  829. 829/// 解码 TIFF Deflate (ZIP) 压缩的字节流
  830. 830/// 支持标准 Huffman 和动态 Huffman 表
  831. 831pub fn tiff_deflate_decode(data : Bytes) -> Array[Byte] raise @types.LoadError {
  832. 832● let len = data.length()
  833. 833 if len < 2 {
  834. 834● raise @types.LoadError::DecodeFailed("TIFF Deflate 数据过短")
  835. 835 }
  836. 836
  837. 837 // Deflate 格式:每个块以 1 位标记位 + 2 位块类型开始
  838. 838 // 块类型:00=未压缩,01=静态 Huffman,10=动态 Huffman,11=保留
  839. 839
  840. 840 let mut bit_pos : Int32 = 0
  841. 841 let output : Array[Byte] = []
  842. 842
  843. 843 // 位读取器
  844. 844 fn read_bits(
  845. 845 data : Bytes,
  846. 846 pos : Int32,
  847. 847 count : Int32,
  848. 848 len : Int32,
  849. 849 ) -> (Int32, Int32) {
  850. 850● let mut code : Int32 = 0
  851. 851 let mut p = pos
  852. 852 let mut i : Int32 = 0
  853. 853 while i < count && p < len * 8 {
  854. 854● let byte_idx = p / 8
  855. 855 let bit_offset = p % 8
  856. 856 if byte_idx < len {
  857. 857● let bit = (data[byte_idx].to_int() >> bit_offset) & 1
  858. 858 code = code | (bit << i)
  859. 859 }
  860. 860 p += 1
  861. 861 i += 1
  862. 862 }
  863. 863 (code, p)
  864. 864 }
  865. 865
  866. 866 // 读取标记位
  867. 867● let (_bits1, new_pos) = read_bits(data, bit_pos, 1, len)
  868. 868 bit_pos = new_pos
  869. 869● let (block_type_bits, final_pos) = read_bits(data, new_pos, 2, len)
  870. 870 bit_pos = final_pos
  871. 871 let block_type = block_type_bits & 0x03
  872. 872 // 字节对齐(未压缩块的数据必须从字节边界开始)
  873. 873 bit_pos = (bit_pos + 7) / 8 * 8
  874. 874
  875. 875 // 目前只支持未压缩块(block_type=0)
  876. 876 if block_type != 0 {
  877. 877● raise @types.LoadError::DecodeFailed("TIFF Deflate 仅支持未压缩块")
  878. 878 }
  879. 879
  880. 880 // 未压缩块:4 字节长度 + 4 字节长度取反 + 数据
  881. 881 // 跳过位读取,直接从字节边界读取
  882. 882 let byte_pos = bit_pos / 8
  883. 883● let len1 = data[byte_pos].to_int() | (data[byte_pos + 1].to_int() << 8)
  884. 884● let len2 = data[byte_pos + 2].to_int() | (data[byte_pos + 3].to_int() << 8)
  885. 885 let block_len = len1
  886. 886 let block_len_inv = len2
  887. 887
  888. 888 if block_len_inv != (block_len ^ 0xFFFF) {
  889. 889● raise @types.LoadError::DecodeFailed("TIFF Deflate 长度校验失败")
  890. 890 }
  891. 891
  892. 892 // 读取数据
  893. 893 let mut i = byte_pos + 4
  894. 894 let end = i + block_len
  895. 895 while i < end && i < len {
  896. 896● output.push(data[i])
  897. 897 i += 1
  898. 898 }
  899. 899
  900. 900 output
  901. 901}