image.pro\recipe\recipe.mbt
87.1% · 148 / 170 points · 525 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # Recipe 层:一次调用完成一件业务事 - 3
/// - 4
/// 本包其余文件是「零实现的再导出」,只有本文件有实现。放这里的原因: - 5
/// Recipe 天然需要 codec(编解码)+ process(算子)两头,而 `image.pro` 是唯一 - 6
/// 已经同时依赖两边的入口包;四个出口(CLI / wasm / MCP / 页面)都能直接用。 - 7
/// - 8
/// 与 Primitive 的区别是**输入输出都是业务语义**(字节进、字节出); - 9
/// 与 CLI 的区别是**不碰文件系统**,所以库包四目标(native/wasm-gc/js/wasm)都能编。 - 10
- 11
///| - 12
/// 运行参数。数值型约束一律用 0 表示"不启用",避免 Option 在四个出口的 ABI 上各写一套。 - 13
pub(all) struct RecipeOpts { - 14
format : @types.ImageFormat - 15
longest : Int32 - 16
max_bytes : Int32 - 17
quality : Int32 - 18
block : Int32 - 19
/// strict 档全图模糊半径;0 表示按 `max(2, block)` 推导。 - 20
blur_radius : Int32 - 21
policy : String - 22
regions : Array[@types.Region] - 23
} - 24
- 25
///| - 26
/// 默认参数:不约束最长边与体积、质量 85、打码块 8、policy=standard、无区域。 - 27
pub fn RecipeOpts::new() -> RecipeOpts { - 28●
{ - 29
format: @types.ImageFormat::Unknown, - 30
longest: 0, - 31
max_bytes: 0, - 32
quality: 85, - 33
block: 8, - 34
blur_radius: 0, - 35
policy: "standard", - 36
regions: [], - 37
} - 38
} - 39
- 40
///| - 41
/// 一步回执。`bytes` 为该步产物的字节数,非编码步填 -1;`width/height` 同理由 -1 占位。 - 42
/// `ms` 是"从上一次打点到这一步结束"的墙钟毫秒,计划层(`plan_recipe`)填 -1(没真跑)。 - 43
pub(all) struct StepRec { - 44
name : String - 45
note : String - 46
width : Int32 - 47
height : Int32 - 48
bytes : Int32 - 49
ms : Double - 50
} - 51
- 52
///| - 53
/// 一次执行里的"上一个打点"。Recipe 全程同步单线程,所以用包级 Ref 而不是给 30 处 - 54
/// `steps.push` 各加两个参数:每处只多一行 `ms: seg_ms(),`。 - 55
let rc_seg : Ref[@bench.Timestamp?] = { val: None, } - 56
- 57
///| - 58
fn rc_seg_start() -> Unit { - 59●
rc_seg.val = Some(@bench.monotonic_clock_start()) - 60
} - 61
- 62
///| - 63
/// 距上一次打点(或 `rc_seg_start`)的毫秒数,并把打点推进到现在。 - 64
/// `monotonic_clock_end` 给微秒,这里除以 1000。 - 65
fn seg_ms() -> Double { - 66●
let now = @bench.monotonic_clock_start() - 67●
let us = match rc_seg.val { - 68●
Some(t) => @bench.monotonic_clock_end(t) - 69●
None => 0.0 - 70
} - 71
rc_seg.val = Some(now) - 72
us / 1000.0 - 73
} - 74
- 75
///| - 76
/// 执行回执:最终像素 + 编码字节 + 逐步记录。 - 77
/// `redacted` / `blurred` 只有 sanitize 有语义,其余 Recipe 恒为 0 / false; - 78
/// `codes` 只有 code-intake 有语义,其余 Recipe 为空数组。 - 79
pub(all) struct RecipeResult { - 80
recipe : String - 81
image : @types.Image - 82
bytes : Bytes - 83
format : @types.ImageFormat - 84
steps : Array[StepRec] - 85
quality : Int32 - 86
redacted : Int32 - 87
blurred : Bool - 88
codes : Array[CodeHit] - 89
} - 90
- 91
///| - 92
/// 已注册的 Recipe 名,顺序即文档顺序。 - 93
pub fn recipe_names() -> Array[String] { - 94●
[ - 95
"sanitize", "thumb", "avatar", "code-intake", "thumb-batch", "doc-scan", "ecom-white", - 96
"redact-id", - 97
] - 98
} - 99
- 100
///| - 101
/// 一句话用途;未知名字返回空串(由 `run_recipe` 负责报错)。 - 102
pub fn recipe_about(name : String) -> String { - 103●
match name { - 104
"sanitize" => - 105●
"剥元数据 + 已知区域块均值打码,输出可外发版本(policy: metadata/standard/strict)" - 106
"thumb" => - 107●
"按最长边等比缩小,可选体积上限(超限自动降质量二分)" - 108●
"avatar" => "中心方形裁切后等比缩放,输出正方形头像" - 109
"code-intake" => - 110●
"识别图里的条码/二维码,输出结构化记录(不改像素,bytes 原样返回)" - 111
"thumb-batch" => - 112●
"多图批量缩略:逐张同一条缩略逻辑,回执给每张尺寸/字节与批量合计(不留解码帧)" - 113
"doc-scan" => - 114●
"拍照文档增强:灰度 + CLAHE 去光照 + 自适应二值化,steps 里记文本行数前后对比" - 115
"ecom-white" => - 116●
"电商白底图:边框估背景 → 距离掩膜 → 最大连通域 → 掩膜收缩 → 白底合成 → 方形补齐" - 117
"redact-id" => - 118●
"证件/票据脱敏:自动命中条码区 + 手工框,实心黑覆盖(不可逆),编码即剥元数据" - 119●
_ => "" - 120
} - 121
} - 122
- 123
///| - 124
/// 该格式是否有质量轴(只有它有,体积二分才成立)。 - 125
fn has_quality_axis(fmt : @types.ImageFormat) -> Bool { - 126●
match fmt { - 127●
@types.ImageFormat::Jpeg => true - 128○
@types.ImageFormat::Webp => true - 129●
_ => false - 130
} - 131
} - 132
- 133
///| - 134
/// 按质量编码一次,错误统一转成库错误码。 - 135
fn encode_at( - 136
img : @types.Image, - 137
fmt : @types.ImageFormat, - 138
q : Int32, - 139
) -> Bytes raise @types.ImageError { - 140●
@lib.save_image_with_quality(img, fmt, q) catch { - 141○
e => raise @types.image_error_from_load(e) - 142
} - 143
} - 144
- 145
///| - 146
/// 解码 + 记录一步。 - 147
fn step_decode( - 148
data : Bytes, - 149
steps : Array[StepRec], - 150
) -> @types.Image raise @types.ImageError { - 151●
let img = @lib.load_from_bytes_auto(data) catch { - 152●
e => raise @types.image_error_from_load(e) - 153
} - 154●
steps.push({ - 155
name: "decode", - 156
note: "", - 157
width: img.width, - 158
height: img.height, - 159
bytes: -1, - 160●
ms: seg_ms(), - 161
}) - 162
img - 163
} - 164
- 165
///| - 166
/// 编码进预算(纯试算,不写 steps):先按给定质量编;超限且格式有质量轴时二分降质量。 - 167
/// 无质量轴或最低档都超限 → `LimitBytes`,真实体积写进消息(调用方据此换格式或缩尺寸)。 - 168
fn encode_fit( - 169
img : @types.Image, - 170
fmt : @types.ImageFormat, - 171
quality : Int32, - 172
max_bytes : Int32, - 173
) -> (Bytes, Int32) raise @types.ImageError { - 174●
let q0 = if quality <= 0 { 85 } else if quality > 100 { 100 } else { quality } - 175●
let first = encode_at(img, fmt, q0) - 176●
let n0 = first.length().to_int() - 177
if max_bytes <= 0 || n0 <= max_bytes { - 178●
return (first, q0) - 179
} - 180●
if !has_quality_axis(fmt) { - 181●
raise @types.ImageError::Process( - 182
@types.ErrorCode::LimitBytes, - 183
"该格式无质量轴,\{n0} 字节已超上限 \{max_bytes}:换 jpeg/webp 或先缩尺寸", - 184
) - 185
} - 186
let mut lo = 1 - 187
let mut hi = q0 - 188
let mut best : Bytes? = None - 189
let mut best_q = 0 - 190
let mut best_n = n0 - 191
while lo <= hi { - 192●
let mid = (lo + hi) / 2 - 193●
let b = encode_at(img, fmt, mid) - 194●
let nb = b.length().to_int() - 195
if nb <= max_bytes { - 196●
best = Some(b) - 197
best_q = mid - 198
best_n = nb - 199
lo = mid + 1 - 200
} else { - 201●
hi = mid - 1 - 202
} - 203
} - 204●
match best { - 205●
Some(b) => (b, best_q) - 206
None => - 207●
raise @types.ImageError::Process( - 208
@types.ErrorCode::LimitBytes, - 209
"质量降到 1 仍有 \{best_n} 字节,超过上限 \{max_bytes}:换格式或先缩尺寸", - 210
) - 211
} - 212
} - 213
- 214
///| - 215
/// 记一步的编码包装:试算成功后把真实质量与体积写进回执。 - 216
fn step_encode( - 217
img : @types.Image, - 218
fmt : @types.ImageFormat, - 219
quality : Int32, - 220
max_bytes : Int32, - 221
steps : Array[StepRec], - 222
) -> (Bytes, Int32) raise @types.ImageError { - 223●
let (bytes, q) = encode_fit(img, fmt, quality, max_bytes) - 224●
steps.push({ - 225
name: "encode", - 226
note: "quality=\{q}", - 227
width: img.width, - 228
height: img.height, - 229●
bytes: bytes.length().to_int(), - 230●
ms: seg_ms(), - 231
}) - 232
(bytes, q) - 233
} - 234
- 235
///| - 236
/// 最长边等比尺寸;`longest` 为 0 或不小于原图长边时返回原尺寸。 - 237
fn fit_longest(img : @types.Image, longest : Int32) -> (Int32, Int32) { - 238●
if longest <= 0 { - 239●
return (img.width, img.height) - 240
} - 241
let lw = img.width - 242
let lh = img.height - 243◐
let long = if lw >= lh { lw } else { lh } - 244
if longest >= long { - 245●
return (lw, lh) - 246
} - 247●
@transform.thumbnail_dims(lw, lh, longest) - 248
} - 249
- 250
///| - 251
/// 编码格式选择:带 alpha 用 png,否则 jpeg;调用方指定(非 Unknown)时优先用指定的。 - 252
fn pick_format( - 253
img : @types.Image, - 254
want : @types.ImageFormat, - 255
) -> @types.ImageFormat { - 256●
match want { - 257
@types.ImageFormat::Unknown => - 258●
if @lib.has_alpha(img) { - 259●
@types.ImageFormat::Png - 260
} else { - 261●
@types.ImageFormat::Jpeg - 262
} - 263●
f => f - 264
} - 265
} - 266
- 267
///| - 268
/// sanitize:policy 决定做几步。 - 269
/// - metadata:只做重编码(EXIF/GPS/ICC/内嵌缩略图不进新容器); - 270
/// - standard:有 regions 就把每块打成均值块,没有就等同 metadata; - 271
/// - strict:没有 regions 时全图打码,之后无论是否有区域都追加全图模糊。 - 272
fn recipe_sanitize( - 273
data : Bytes, - 274
opts : RecipeOpts, - 275
) -> RecipeResult raise @types.ImageError { - 276●
let steps : Array[StepRec] = [] - 277
let policy = opts.policy - 278
if policy != "metadata" && policy != "standard" && policy != "strict" { - 279●
raise @types.ImageError::Process( - 280
@types.ErrorCode::InvalidArgument, - 281
"policy 只能是 metadata / standard / strict(收到 \{policy})", - 282
) - 283
} - 284●
let mut img = step_decode(data, steps) - 285
let use_regions = policy == "standard" || policy == "strict" - 286
let use_blur = policy == "strict" - 287
let mut redacted = 0 - 288
if use_regions { - 289●
if opts.regions.length() == 0 { - 290●
if use_blur { - 291●
img = @filter.redact_blocks_all(img, opts.block) - 292
redacted = 1 - 293
} - 294
} else { - 295●
for r in opts.regions { - 296●
img = @filter.redact_blocks(img, r, opts.block) - 297
redacted += 1 - 298
} - 299
} - 300
} - 301
if use_blur { - 302●
let radius = if opts.blur_radius > 0 { - 303●
opts.blur_radius - 304●
} else if opts.block < 2 { - 305○
2 - 306
} else { - 307●
opts.block - 308
} - 309●
img = @filter.box_blur(img, radius) catch { - 310○
e => raise @types.image_error_from_load(e) - 311
} - 312
} - 313●
steps.push({ - 314
name: "policy", - 315
note: "\{policy} regions=\{redacted} blur=\{use_blur}", - 316
width: -1, - 317
height: -1, - 318
bytes: -1, - 319●
ms: seg_ms(), - 320
}) - 321●
let fmt0 = pick_format(img, opts.format) - 322●
let (bytes, q) = step_encode(img, fmt0, opts.quality, opts.max_bytes, steps) - 323
{ - 324
recipe: "sanitize", - 325
image: img, - 326
bytes, - 327
format: fmt0, - 328
steps, - 329
quality: q, - 330
redacted, - 331
blurred: use_blur, - 332
codes: [], - 333
} - 334
} - 335
- 336
///| - 337
/// thumb:只缩不裁,纵横比不变。 - 338
fn recipe_thumb( - 339
data : Bytes, - 340
opts : RecipeOpts, - 341
) -> RecipeResult raise @types.ImageError { - 342●
let steps : Array[StepRec] = [] - 343●
let mut img = step_decode(data, steps) - 344●
let (tw, th) = fit_longest(img, opts.longest) - 345
if tw != img.width || th != img.height { - 346●
img = @transform.resize_to_contain( - 347
img, - 348
tw, - 349
th, - 350●
Array::make(img.channels, (255 : Byte)), - 351
) catch { - 352○
e => raise @types.image_error_from_load(e) - 353
} - 354●
steps.push({ - 355
name: "resize", - 356
note: "", - 357
width: img.width, - 358
height: img.height, - 359
bytes: -1, - 360●
ms: seg_ms(), - 361
}) - 362
} - 363●
let fmt0 = pick_format(img, opts.format) - 364
let mut cur = img - 365
let mut res : (Bytes, Int32)? = None - 366
let mut tries = 0 - 367
while res is None && tries < 5 { - 368●
let attempt = Some(encode_fit(cur, fmt0, opts.quality, opts.max_bytes)) catch { - 369●
@types.ImageError::Process(@types.ErrorCode::LimitBytes, _) => None - 370○
e => raise e - 371
} - 372●
match attempt { - 373●
Some(v) => res = Some(v) - 374●
None => { - 375
// 质量已到底仍装不下:按 4/5 缩长边再来一次(thumb 的语义就是"缩到装得下") - 376
if opts.max_bytes <= 0 { - 377○
break - 378
} - 379◐
let side = if cur.width >= cur.height { cur.width } else { cur.height } - 380
let next = side * 4 / 5 - 381
if next < 16 || next >= side { - 382○
break - 383
} - 384●
let (nw, nh) = fit_longest(cur, next) - 385●
cur = @transform.resize_to_contain( - 386
cur, - 387
nw, - 388
nh, - 389●
Array::make(cur.channels, (255 : Byte)), - 390
) catch { - 391○
e => raise @types.image_error_from_load(e) - 392
} - 393●
steps.push({ - 394
name: "resize", - 395
note: "fit-budget", - 396
width: cur.width, - 397
height: cur.height, - 398
bytes: -1, - 399●
ms: seg_ms(), - 400
}) - 401
tries = tries + 1 - 402
} - 403
} - 404
} - 405●
match res { - 406●
Some((b, q0)) => { - 407●
steps.push({ - 408
name: "encode", - 409
note: "quality=\{q0}", - 410
width: cur.width, - 411
height: cur.height, - 412●
bytes: b.length().to_int(), - 413●
ms: seg_ms(), - 414
}) - 415
{ - 416
recipe: "thumb", - 417
image: cur, - 418
bytes: b, - 419
format: fmt0, - 420
steps, - 421
quality: q0, - 422
redacted: 0, - 423
blurred: false, - 424
codes: [], - 425
} - 426
} - 427●
None => { - 428●
let n0 = @lib.save_image_with_quality(cur, fmt0, 1) catch { - 429○
e => raise @types.image_error_from_load(e) - 430
} - 431
raise @types.ImageError::Process( - 432
@types.ErrorCode::LimitBytes, - 433
"缩到 \{cur.width}x\{cur.height} 且质量 1 仍有 \{n0.length().to_int()} 字节,超过上限 \{opts.max_bytes}:换格式或调高上限", - 434
) - 435
} - 436
} - 437
} - 438
- 439
///| - 440
/// avatar:先按中心取正方形,再缩到目标边长(`longest` 即边长,0 默认 256)。 - 441
fn recipe_avatar( - 442
data : Bytes, - 443
opts : RecipeOpts, - 444
) -> RecipeResult raise @types.ImageError { - 445●
let steps : Array[StepRec] = [] - 446●
let mut img = step_decode(data, steps) - 447◐
let side = if img.width < img.height { img.width } else { img.height } - 448
let ox = (img.width - side) / 2 - 449
let oy = (img.height - side) / 2 - 450
if side != img.width || side != img.height { - 451●
img = @transform.crop(img, ox, oy, side, side) catch { - 452○
e => raise @types.image_error_from_load(e) - 453
} - 454●
steps.push({ - 455
name: "crop", - 456
note: "center", - 457
width: side, - 458
height: side, - 459
bytes: -1, - 460●
ms: seg_ms(), - 461
}) - 462
} - 463●
let target = if opts.longest <= 0 { 256 } else { opts.longest } - 464
if target != side { - 465●
img = @transform.resize_to_cover(img, target, target) catch { - 466○
e => raise @types.image_error_from_load(e) - 467
} - 468●
steps.push({ - 469
name: "resize", - 470
note: "", - 471
width: target, - 472
height: target, - 473
bytes: -1, - 474●
ms: seg_ms(), - 475
}) - 476
} - 477●
let fmt0 = pick_format(img, opts.format) - 478●
let (bytes, q) = step_encode(img, fmt0, opts.quality, opts.max_bytes, steps) - 479
{ - 480
recipe: "avatar", - 481
image: img, - 482
bytes, - 483
format: fmt0, - 484
steps, - 485
quality: q, - 486
redacted: 0, - 487
blurred: false, - 488
codes: [], - 489
} - 490
} - 491
- 492
///| - 493
/// 统一入口:名字 → 实现。未知名字报 `invalid_argument` 并列出可用名, - 494
/// 不返回空结果(空结果会让调用方以为"处理成功了但输出为空")。 - 495
pub fn run_recipe( - 496
name : String, - 497
data : Bytes, - 498
opts : RecipeOpts, - 499
) -> RecipeResult raise @types.ImageError { - 500●
rc_seg_start() - 501●
match name { - 502●
"sanitize" => recipe_sanitize(data, opts) - 503●
"thumb" => recipe_thumb(data, opts) - 504●
"avatar" => recipe_avatar(data, opts) - 505●
"code-intake" => recipe_code_intake(data, opts) - 506●
"thumb-batch" => recipe_thumb_batch(data, opts) - 507●
"doc-scan" => recipe_doc_scan(data, opts) - 508●
"ecom-white" => recipe_ecom_white(data, opts) - 509●
"redact-id" => recipe_redact_id(data, opts) - 510●
_ => { - 511
let mut names = "" - 512●
let all = recipe_names() - 513●
for i in 0..<all.length() { - 514●
if i > 0 { - 515●
names = names + ", " - 516
} - 517
names = names + all[i] - 518
} - 519
raise @types.ImageError::Process( - 520
@types.ErrorCode::InvalidArgument, - 521
"未知 recipe: \{name}(可用: \{names})", - 522
) - 523
} - 524
} - 525
}