image.codec\codec\bmp_encode.mbt
97.1% · 68 / 70 points · 92 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # BMP 编码 BMP Encode - 3
/// - 4
/// BMP 图像格式编码 - 5
/// BMP 图像格式编码 BMP image format encoding - 6
// 纯 MoonBit BMP 编码(全目标可用:native/wasm/js) - 7
// 24-bit BMP, BITMAPINFOHEADER, bottom-up, BGR, 4字节行对齐 - 8
- 9
///| - 10
/// 写入 4 字节小端整数 - 11
fn bmp_write_i32_le(out : Array[Byte], val : Int32) -> Unit { - 12●
out.push((val & 0xFF).to_byte()) - 13●
out.push(((val >> 8) & 0xFF).to_byte()) - 14●
out.push(((val >> 16) & 0xFF).to_byte()) - 15●
out.push(((val >> 24) & 0xFF).to_byte()) - 16
} - 17
- 18
///| - 19
/// BMP 编码(纯 MoonBit,全目标可用)。 - 20
pub fn encode_bmp_pure(img : @types.Image) -> Bytes { - 21●
let width = img.width - 22
let height = img.height - 23
let channels = img.channels - 24
let data = img.data - 25
let row_padded = (width * 3 + 3) & 0x7FFFFFFC - 26
let pixel_size = row_padded * height - 27
let file_size = 54 + pixel_size - 28
let out : Array[Byte] = [] - 29
// BMP File Header (14 bytes) - 30●
out.push(b'\x42') - 31●
out.push(b'\x4D') - 32●
bmp_write_i32_le(out, file_size) - 33●
out.push(b'\x00') - 34●
out.push(b'\x00') - 35●
out.push(b'\x00') - 36●
out.push(b'\x00') - 37●
out.push(b'\x36') - 38●
out.push(b'\x00') - 39●
out.push(b'\x00') - 40●
out.push(b'\x00') - 41
// DIB Header (40 bytes) - 42●
out.push(b'\x28') - 43●
out.push(b'\x00') - 44●
out.push(b'\x00') - 45●
out.push(b'\x00') - 46●
bmp_write_i32_le(out, width) - 47●
bmp_write_i32_le(out, height) - 48●
out.push(b'\x01') - 49●
out.push(b'\x00') - 50●
out.push(b'\x18') - 51●
out.push(b'\x00') - 52●
out.push(b'\x00') - 53●
out.push(b'\x00') - 54●
out.push(b'\x00') - 55●
out.push(b'\x00') - 56●
bmp_write_i32_le(out, pixel_size) - 57●
out.push(b'\x00') - 58●
out.push(b'\x00') - 59●
out.push(b'\x00') - 60●
out.push(b'\x00') - 61●
out.push(b'\x00') - 62●
out.push(b'\x00') - 63●
out.push(b'\x00') - 64●
out.push(b'\x00') - 65●
out.push(b'\x00') - 66●
out.push(b'\x00') - 67●
out.push(b'\x00') - 68●
out.push(b'\x00') - 69●
out.push(b'\x00') - 70●
out.push(b'\x00') - 71●
out.push(b'\x00') - 72●
out.push(b'\x00') - 73
// Pixel data (bottom-up, BGR, 4-byte row padding) - 74
for y in 0..<height { - 75●
let ry = height - 1 - y - 76
let row_start = ry * width * channels - 77
for x in 0..<width { - 78●
let idx = row_start + x * channels - 79●
let r = data[idx].to_int() - 80◐
let g = if channels >= 2 { data[idx + 1].to_int() } else { r } - 81◐
let b = if channels >= 3 { data[idx + 2].to_int() } else { r } - 82●
out.push(b.to_byte()) - 83●
out.push(g.to_byte()) - 84●
out.push(r.to_byte()) - 85
} - 86
let padding = row_padded - width * 3 - 87
for _ in 0..<padding { - 88●
out.push(b'\x00') - 89
} - 90
} - 91●
Bytes::from_array(out) - 92
}