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