image.codec\lib\best_format.mbt

60.6% · 20 / 33 points · 116 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # 自动选格式(best_format)
  3. 3///
  4. 4/// 两种用法,别混淆:
  5. 5/// - `best_format(img)`:**不编码**的启发式猜测,毫秒级,适合给日志/前端提示;
  6. 6/// - `encode_best(img, quality)`:真的把候选格式各编一遍,挑最小的返回——这是"体积真值",
  7. 7/// 代价是 N 次编码。出口想省体积就用它,想省 CPU 就先用 `best_format` 猜。
  8. 8
  9. 9///|
  10. 10/// 一次候选编码的结果。
  11. 11#derive(@debug.Debug)
  12. 12pub(all) struct EncodedImage {
  13. 13 format : @types.ImageFormat
  14. 14 bytes : Bytes
  15. 15}
  16. 16
  17. 17///|
  18. 18/// 图像是否带"真的透明"(4 通道且存在 alpha < 255 的像素)。
  19. 19/// 3 通道一律视为不透明;1 通道视为不透明。
  20. 20pub fn has_alpha(img : @types.Image) -> Bool {
  21. 21● if img.channels != 4 {
  22. 22● return false
  23. 23 }
  24. 24 let n = img.width * img.height
  25. 25 for i in 0..<n {
  26. 26● if img.data[i * 4 + 3] != b'\xff' {
  27. 27● return true
  28. 28 }
  29. 29 }
  30. 30 false
  31. 31}
  32. 32
  33. 33///|
  34. 34/// 廉价启发式:不编码,只按"有无透明"给一个偏好格式。
  35. 35/// 不透明图默认给 `Jpeg`(照片类通常最省);带透明给 `Webp`(无损且有 alpha)。
  36. 36/// 想要真实最小体积请用 `encode_best`。
  37. 37pub fn best_format(img : @types.Image) -> @types.ImageFormat {
  38. 38○ if has_alpha(img) {
  39. 39○ @types.ImageFormat::Webp
  40. 40 } else {
  41. 41○ @types.ImageFormat::Jpeg
  42. 42 }
  43. 43}
  44. 44
  45. 45///|
  46. 46/// 候选格式集合:带透明走 WebP / PNG / QOI(无损且支持 alpha),
  47. 47/// 不透明走 JPEG / WebP / QOI / PNG。
  48. 48fn candidates(img : @types.Image) -> Array[@types.ImageFormat] {
  49. 49● if has_alpha(img) {
  50. 50○ [@types.ImageFormat::Webp, @types.ImageFormat::Png, @types.ImageFormat::Qoi]
  51. 51 } else {
  52. 52● [
  53. 53 @types.ImageFormat::Jpeg,
  54. 54 @types.ImageFormat::Webp,
  55. 55 @types.ImageFormat::Qoi,
  56. 56 @types.ImageFormat::Png,
  57. 57 ]
  58. 58 }
  59. 59}
  60. 60
  61. 61///|
  62. 62/// 把候选格式各编一遍,返回体积最小的那个(同体积时按候选顺序取前者)。
  63. 63/// 单个候选编码失败会被跳过;全部失败才报 `ProcessFailed`。
  64. 64/// `quality` 传给 `save_image_with_quality`(当前仅 JPEG 生效,无损格式忽略)。
  65. 65pub fn encode_best(
  66. 66 img : @types.Image,
  67. 67 quality : Int32,
  68. 68) -> EncodedImage raise @types.ImageError {
  69. 69● let cands = candidates(img)
  70. 70 let mut best : (Int32, Bytes, @types.ImageFormat)? = None
  71. 71 for fmt in cands {
  72. 72● let encoded = Some(save_image_with_quality(img, fmt, quality)) catch {
  73. 73○ _ => None
  74. 74 }
  75. 75● match encoded {
  76. 76● Some(bytes) => {
  77. 77● let size = bytes.length()
  78. 78● match best {
  79. 79● None => best = Some((size, bytes, fmt))
  80. 80 Some((best_size, _, _)) =>
  81. 81● if size < best_size {
  82. 82● best = Some((size, bytes, fmt))
  83. 83 }
  84. 84 }
  85. 85 }
  86. 86○ None => ()
  87. 87 }
  88. 88 }
  89. 89● match best {
  90. 90● Some((_, bytes, fmt)) => { format: fmt, bytes, }
  91. 91 None =>
  92. 92○ raise @types.ImageError::Process(
  93. 93 @types.ErrorCode::ProcessFailed,
  94. 94 "encode_best: 所有候选格式都编码失败",
  95. 95 )
  96. 96 }
  97. 97}
  98. 98
  99. 99///|
  100. 100/// 带体积上限的 `encode_best`:最小结果仍超过 `max_bytes` 就报
  101. 101/// `Budget(LimitBytes)`(不返回超限数据,避免调用方写出超限文件)。
  102. 102pub fn encode_best_limited(
  103. 103 img : @types.Image,
  104. 104 quality : Int32,
  105. 105 max_bytes : Int64,
  106. 106) -> EncodedImage raise @types.ImageError {
  107. 107○ let best = encode_best(img, quality)
  108. 108○ let size = best.bytes.length().to_int64()
  109. 109 if max_bytes > 0L && size > max_bytes {
  110. 110○ raise @types.ImageError::Budget(
  111. 111 @types.ErrorCode::LimitBytes,
  112. 112 "encode_best: 最小体积 \{size} 字节仍超过上限 \{max_bytes}",
  113. 113 )
  114. 114 }
  115. 115 best
  116. 116}