image.codec\codec\pnm_encode.mbt
100% · 39 / 39 points · 83 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # PNM 编码 PNM Encode - 3
/// - 4
/// PNM 图像格式编码 - 5
/// PNM 图像格式编码 PNM image format encoding - 6
// 纯 MoonBit PNM 格式编码器:PPM (P6) + PGM (P5) - 7
// 移植自 src/format/pnm_encode.mbt,仅替换类型引用: - 8
// @core.Image -> @types.Image - 9
- 10
///| - 11
/// 编码为 PPM (P6 binary RGB) 格式。 - 12
/// 灰度输入自动转为 RGB,RGBA 输入丢弃 alpha。 - 13
pub fn encode_ppm_pure(img : @types.Image) -> Bytes { - 14●
let w = img.width - 15
let h = img.height - 16
let ch = img.channels - 17
let n = w * h - 18
// 构建 RGB 像素数据 - 19●
let pixel_data : Array[Byte] = Array::make(n * 3, b'\x00') - 20
for i in 0..<n { - 21●
let r = img.data[i * ch] - 22●
let g = if ch >= 2 { img.data[i * ch + 1] } else { r } - 23●
let b = if ch >= 3 { img.data[i * ch + 2] } else { r } - 24
pixel_data[i * 3] = r - 25
pixel_data[i * 3 + 1] = g - 26
pixel_data[i * 3 + 2] = b - 27
} - 28
// 头部: "P6\n{w} {h}\n255\n" - 29●
let header = "P6\n" + w.to_string() + " " + h.to_string() + "\n255\n" - 30●
let header_bytes = @encoding/utf8.encode(header) - 31
let result : Array[Byte] = [] - 32●
for i in 0..<header_bytes.length() { - 33●
result.push(header_bytes[i]) - 34
} - 35●
for i in 0..<pixel_data.length() { - 36●
result.push(pixel_data[i]) - 37
} - 38●
Bytes::from_array(result) - 39
} - 40
- 41
///| - 42
/// 编码为 PGM (P5 binary grayscale) 格式。 - 43
/// RGB 输入自动转为灰度(BT.601),RGBA 丢弃 alpha。 - 44
pub fn encode_pgm_pure(img : @types.Image) -> Bytes { - 45●
let w = img.width - 46
let h = img.height - 47
let ch = img.channels - 48
let n = w * h - 49
// 构建灰度像素数据 - 50●
let pixel_data : Array[Byte] = Array::make(n, b'\x00') - 51
for i in 0..<n { - 52●
if ch == 1 { - 53●
pixel_data[i] = img.data[i] - 54
} else { - 55●
let r = img.data[i * ch].to_int() - 56●
let g = img.data[i * ch + 1].to_int() - 57●
let b = img.data[i * ch + 2].to_int() - 58●
pixel_data[i] = ((r * 299 + g * 587 + b * 114) / 1000).to_byte() - 59
} - 60
} - 61
// 头部: "P5\n{w} {h}\n255\n" - 62●
let header = "P5\n" + w.to_string() + " " + h.to_string() + "\n255\n" - 63●
let header_bytes = @encoding/utf8.encode(header) - 64
let result : Array[Byte] = [] - 65●
for i in 0..<header_bytes.length() { - 66●
result.push(header_bytes[i]) - 67
} - 68●
for i in 0..<pixel_data.length() { - 69●
result.push(pixel_data[i]) - 70
} - 71●
Bytes::from_array(result) - 72
} - 73
- 74
///| - 75
/// 自动选择 PNM 格式编码。 - 76
/// channels <= 1 → PGM (P5),否则 → PPM (P6)。 - 77
pub fn encode_pnm_pure(img : @types.Image) -> Bytes { - 78●
if img.channels <= 1 { - 79●
encode_pgm_pure(img) - 80
} else { - 81●
encode_ppm_pure(img) - 82
} - 83
}