image.domain\util\image_util.mbt
95.8% · 23 / 24 points · 96 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 图像工具 util/image_util - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 图像几何增强(纯 MoonBit):pad / add_border - 7
- 8
///| - 9
/// 在图像四周填充指定颜色,生成新尺寸 (width+2*px, height+2*py) 的新图像。 - 10
/// pad_color 长度应等于 channels,不足则循环使用。 - 11
pub fn pad( - 12
img : @types.Image, - 13
px : Int32, - 14
py : Int32, - 15
pad_color : Array[Byte], - 16
) -> @types.Image raise @types.LoadError { - 17●
if px < 0 || py < 0 { - 18●
raise @types.LoadError::DecodeFailed("pad 填充必须非负") - 19
} - 20
let ch = img.channels - 21
let new_w = img.width + 2 * px - 22
let new_h = img.height + 2 * py - 23●
let out : Array[Byte] = Array::make(new_w * new_h * ch, b'\x00') - 24●
let color_len = pad_color.length() - 25
if color_len == 0 { - 26●
raise @types.LoadError::DecodeFailed("pad_color 不能为空") - 27
} - 28
// 填充 - 29
for y in 0..<new_h { - 30●
for x in 0..<new_w { - 31●
let dst_off = (y * new_w + x) * ch - 32
if x >= px && x < px + img.width && y >= py && y < py + img.height { - 33
// 拷贝原始像素 - 34●
let src_off = ((y - py) * img.width + (x - px)) * ch - 35
for c in 0..<ch { - 36●
out[dst_off + c] = img.data[src_off + c] - 37
} - 38
} else { - 39
// 填充颜色 - 40●
for c in 0..<ch { - 41●
out[dst_off + c] = pad_color[c % color_len] - 42
} - 43
} - 44
} - 45
} - 46
@types.Image::{ - 47
width: new_w, - 48
height: new_h, - 49
channels: ch, - 50●
data: Bytes::from_array(out), - 51
} - 52
} - 53
- 54
///| - 55
/// 添加边框。top/right/bottom/left 分别为四边边框宽度,border_color 为边框颜色。 - 56
pub fn add_border( - 57
img : @types.Image, - 58
top : Int32, - 59
right : Int32, - 60
bottom : Int32, - 61
left : Int32, - 62
border_color : Array[Byte], - 63
) -> @types.Image raise @types.LoadError { - 64●
if top < 0 || right < 0 || bottom < 0 || left < 0 { - 65○
raise @types.LoadError::DecodeFailed("border 宽度必须非负") - 66
} - 67
let ch = img.channels - 68
let new_w = img.width + left + right - 69
let new_h = img.height + top + bottom - 70●
let out : Array[Byte] = Array::make(new_w * new_h * ch, b'\x00') - 71●
let color_len = border_color.length() - 72
if color_len == 0 { - 73●
raise @types.LoadError::DecodeFailed("border_color 不能为空") - 74
} - 75
for y in 0..<new_h { - 76●
for x in 0..<new_w { - 77●
let dst_off = (y * new_w + x) * ch - 78
if x >= left && x < left + img.width && y >= top && y < top + img.height { - 79●
let src_off = ((y - top) * img.width + (x - left)) * ch - 80
for c in 0..<ch { - 81●
out[dst_off + c] = img.data[src_off + c] - 82
} - 83
} else { - 84●
for c in 0..<ch { - 85●
out[dst_off + c] = border_color[c % color_len] - 86
} - 87
} - 88
} - 89
} - 90
@types.Image::{ - 91
width: new_w, - 92
height: new_h, - 93
channels: ch, - 94●
data: Bytes::from_array(out), - 95
} - 96
}