image.codec\codec\ico_codec.mbt

90.1% · 164 / 182 points · 376 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/// # ICO/CUR 编解码 ICO/CUR Codec
  3. 3///
  4. 4/// Windows ICO/CUR 图标格式编解码 Windows ICO/CUR icon format encoding/decoding
  5. 5// 纯 MoonBit ICO/CUR 编解码(全目标可用:native/wasm/js)
  6. 6// ICO 规范: https://en.wikipedia.org/wiki/ICO_(file_format)
  7. 7// CUR 规范: 与 ICO 相同,但 type=2 且 ICONDIRENTRY 的 planes/bitcount 字段为热点坐标
  8. 8// 子图像可为 BMP(无文件头,height 翻倍含 AND 掩码)或 PNG
  9. 9
  10. 10///|
  11. 11/// ICO/CUR 目录条目
  12. 12priv struct IconDirEntry {
  13. 13 width : Int32
  14. 14 height : Int32
  15. 15 byte_size : Int32
  16. 16 offset : Int32
  17. 17}
  18. 18
  19. 19///|
  20. 20/// 解析 ICO/CUR 目录条目,返回 (icon_type, entries)
  21. 21fn parse_ico_header(
  22. 22 data : Bytes,
  23. 23) -> (Int32, Array[IconDirEntry]) raise @types.LoadError {
  24. 24● let len = data.length()
  25. 25 if len < 6 {
  26. 26● raise @types.LoadError::DecodeFailed("ICO/CUR 数据过短")
  27. 27 }
  28. 28● let icon_type = read_u16_le(data, 2)
  29. 29● let count = read_u16_le(data, 4)
  30. 30 if icon_type != 1 && icon_type != 2 {
  31. 31● raise @types.LoadError::DecodeFailed("ICO/CUR type 无效")
  32. 32 }
  33. 33 if count == 0 {
  34. 34● raise @types.LoadError::DecodeFailed("ICO/CUR 无图像条目")
  35. 35 }
  36. 36 if len < 6 + count * 16 {
  37. 37● raise @types.LoadError::DecodeFailed("ICO/CUR 目录数据不完整")
  38. 38 }
  39. 39 let entries : Array[IconDirEntry] = []
  40. 40 for i in 0..<count {
  41. 41● let base = 6 + i * 16
  42. 42● let w = data[base].to_int()
  43. 43● let h = data[base + 1].to_int()
  44. 44● let byte_size = read_u32_le(data, base + 8)
  45. 45● let offset = read_u32_le(data, base + 12)
  46. 46● entries.push(IconDirEntry::{
  47. 47 width: if w == 0 {
  48. 48● 256
  49. 49 } else {
  50. 50● w
  51. 51 },
  52. 52 height: if h == 0 {
  53. 53● 256
  54. 54 } else {
  55. 55● h
  56. 56 },
  57. 57 byte_size,
  58. 58 offset,
  59. 59 })
  60. 60 }
  61. 61 (icon_type, entries)
  62. 62}
  63. 63
  64. 64///|
  65. 65/// 从 ICO/CUR 中选择最佳条目(面积最大优先)
  66. 66fn select_best_entry(entries : Array[IconDirEntry]) -> Int32 {
  67. 67● let mut best_idx = 0
  68. 68 let mut best_area = 0
  69. 69● for i in 0..<entries.length() {
  70. 70● let area = entries[i].width * entries[i].height
  71. 71 if area > best_area {
  72. 72● best_area = area
  73. 73 best_idx = i
  74. 74 }
  75. 75 }
  76. 76 best_idx
  77. 77}
  78. 78
  79. 79///|
  80. 80/// 解码 BMP 子图像(ICO 内嵌,无文件头,height 翻倍)
  81. 81fn decode_ico_bmp_subimage(
  82. 82 data : Bytes,
  83. 83 offset : Int32,
  84. 84 byte_size : Int32,
  85. 85) -> @types.Image raise @types.LoadError {
  86. 86● let len = data.length()
  87. 87 if offset + 40 > len {
  88. 88○ raise @types.LoadError::DecodeFailed("ICO BMP 子图像数据不完整")
  89. 89 }
  90. 90● let dib_size = read_u32_le(data, offset)
  91. 91 if dib_size < 40 {
  92. 92● raise @types.LoadError::DecodeFailed("ICO BMP DIB 头过短")
  93. 93 }
  94. 94● let width = read_u32_le(data, offset + 4)
  95. 95● let height2 = read_u32_le(data, offset + 8)
  96. 96● let bpp = read_u16_le(data, offset + 14)
  97. 97● let compression = read_u32_le(data, offset + 16)
  98. 98 if compression != 0 {
  99. 99● raise @types.LoadError::DecodeFailed("ICO BMP 子图像不支持压缩")
  100. 100 }
  101. 101 let height = height2 / 2
  102. 102 if width <= 0 || height <= 0 {
  103. 103● raise @types.LoadError::DecodeFailed("ICO BMP 子图像尺寸无效")
  104. 104 }
  105. 105◐ let abs_w = if width < 0 { -width } else { width }
  106. 106◐ let abs_h = if height < 0 { -height } else { height }
  107. 107 let color_offset = offset + dib_size
  108. 108 let bytes_per_pixel = bpp / 8
  109. 109 let row_size = (abs_w * bytes_per_pixel + 3) / 4 * 4
  110. 110 // AND 掩码:1 bit/pixel,每行 4 字节对齐
  111. 111 let and_row_size = (abs_w + 31) / 32 * 4
  112. 112 let out_channels = 4
  113. 113 let pixel_count = abs_w * abs_h
  114. 114● let pixels : Array[Byte] = Array::make(pixel_count * out_channels, b'\x00')
  115. 115 // 色彩数据自下而上
  116. 116 for file_row in 0..<abs_h {
  117. 117● let out_row = abs_h - 1 - file_row
  118. 118 let row_start = color_offset + file_row * row_size
  119. 119 for x in 0..<abs_w {
  120. 120● let px_off = row_start + x * bytes_per_pixel
  121. 121 if px_off + bytes_per_pixel > len {
  122. 122● raise @types.LoadError::DecodeFailed("ICO BMP 像素数据越界")
  123. 123 }
  124. 124● let b = data[px_off].to_int()
  125. 125● let g = data[px_off + 1].to_int()
  126. 126● let r = data[px_off + 2].to_int()
  127. 127● let a = if bpp == 32 { data[px_off + 3].to_int() } else { 255 }
  128. 128 let out_idx = (out_row * abs_w + x) * out_channels
  129. 129● pixels[out_idx] = r.to_byte()
  130. 130● pixels[out_idx + 1] = g.to_byte()
  131. 131● pixels[out_idx + 2] = b.to_byte()
  132. 132● pixels[out_idx + 3] = a.to_byte()
  133. 133 }
  134. 134 }
  135. 135 // 处理 AND 掩码(1-bit 透明度),仅对非 32-bit 有效
  136. 136 if bpp != 32 {
  137. 137● let and_offset = color_offset + abs_h * row_size
  138. 138 for file_row in 0..<abs_h {
  139. 139● let out_row = abs_h - 1 - file_row
  140. 140 let and_row_start = and_offset + file_row * and_row_size
  141. 141 for x in 0..<abs_w {
  142. 142● let byte_idx = x / 8
  143. 143 let bit_idx = 7 - x % 8
  144. 144 if and_row_start + byte_idx < len {
  145. 145● let mask_byte = data[and_row_start + byte_idx].to_int()
  146. 146 if ((mask_byte >> bit_idx) & 1) == 1 {
  147. 147● let out_idx = (out_row * abs_w + x) * out_channels
  148. 148 pixels[out_idx + 3] = b'\x00'
  149. 149 }
  150. 150 }
  151. 151 }
  152. 152 }
  153. 153 }
  154. 154 let _ = byte_size
  155. 155 @types.Image::{
  156. 156 width: abs_w,
  157. 157 height: abs_h,
  158. 158 channels: out_channels,
  159. 159● data: Bytes::from_array(pixels),
  160. 160 }
  161. 161}
  162. 162
  163. 163///|
  164. 164/// 解码 ICO 字节流为 Image(选择面积最大的子图像),支持 BMP 子图像(24/32-bit)和 PNG 子图像 Decode ICO byte stream to Image (selects largest sub-image by area), Supports BMP sub-images (24/32-bit) and PNG sub-images
  165. 165
  166. 166///|
  167. 167/// 参数 Parameters:
  168. 168/// - `data` - ICO 字节流 ICO byte stream
  169. 169///
  170. 170/// 返回 Return:
  171. 171/// - 解码后的 8-bit Image Decoded 8-bit Image
  172. 172///
  173. 173/// 错误 Errors:
  174. 174/// - `LoadError::DecodeFailed` - 数据过短、ICO 签名无效、无可用子图像 Data too short, invalid ICO signature, no usable sub-image
  175. 175pub fn decode_ico_pure(data : Bytes) -> @types.Image raise @types.LoadError {
  176. 176● let (icon_type, entries) = parse_ico_header(data)
  177. 177 if icon_type != 1 {
  178. 178● raise @types.LoadError::DecodeFailed("ICO type 应为 1")
  179. 179 }
  180. 180● let best = select_best_entry(entries)
  181. 181 let entry = entries[best]
  182. 182● let len = data.length()
  183. 183 if entry.offset + entry.byte_size > len {
  184. 184● raise @types.LoadError::DecodeFailed("ICO 子图像数据越界")
  185. 185 }
  186. 186● if is_png_signature(data, entry.offset) {
  187. 187 // PNG 子图像:提取子字节流并委托 PNG 解码器
  188. 188○ let sub : Array[Byte] = []
  189. 189 for i in 0..<entry.byte_size {
  190. 190○ sub.push(data[entry.offset + i])
  191. 191 }
  192. 192○ decode_png_pure(Bytes::from_array(sub))
  193. 193 } else {
  194. 194● decode_ico_bmp_subimage(data, entry.offset, entry.byte_size)
  195. 195 }
  196. 196}
  197. 197
  198. 198///|
  199. 199/// 解码 CUR 字节流为 Image(选择面积最大的子图像) Decode CUR byte stream to Image (selects largest sub-image by area)
  200. 200///
  201. 201/// 参数 Parameters:
  202. 202/// - `data` - CUR 字节流 CUR byte stream
  203. 203///
  204. 204/// 返回 Return:
  205. 205/// - 解码后的 8-bit Image Decoded 8-bit Image
  206. 206///
  207. 207/// 错误 Errors:
  208. 208/// - `LoadError::DecodeFailed` - 数据过短、CUR 签名无效、无可用子图像 Data too short, invalid CUR signature, no usable sub-image
  209. 209pub fn decode_cur_pure(data : Bytes) -> @types.Image raise @types.LoadError {
  210. 210● let (icon_type, entries) = parse_ico_header(data)
  211. 211 if icon_type != 2 {
  212. 212● raise @types.LoadError::DecodeFailed("CUR type 应为 2")
  213. 213 }
  214. 214● let best = select_best_entry(entries)
  215. 215 let entry = entries[best]
  216. 216● let len = data.length()
  217. 217 if entry.offset + entry.byte_size > len {
  218. 218○ raise @types.LoadError::DecodeFailed("CUR 子图像数据越界")
  219. 219 }
  220. 220● if is_png_signature(data, entry.offset) {
  221. 221○ let sub : Array[Byte] = []
  222. 222 for i in 0..<entry.byte_size {
  223. 223○ sub.push(data[entry.offset + i])
  224. 224 }
  225. 225○ decode_png_pure(Bytes::from_array(sub))
  226. 226 } else {
  227. 227● decode_ico_bmp_subimage(data, entry.offset, entry.byte_size)
  228. 228 }
  229. 229}
  230. 230
  231. 231///|
  232. 232/// 将单个 Image 编码为 ICO 内嵌 BMP 子图像(32-bit BGRA + AND 掩码)
  233. 233/// 返回 (子图像字节数组, 宽, 高)
  234. 234fn encode_ico_bmp_subimage(img : @types.Image) -> (Array[Byte], Int32, Int32) {
  235. 235● let width = img.width
  236. 236 let height = img.height
  237. 237 let channels = img.channels
  238. 238 let data = img.data
  239. 239 let out : Array[Byte] = []
  240. 240 // BITMAPINFOHEADER (40 bytes)
  241. 241● write_u32_le(out, 40) // biSize
  242. 242● write_u32_le(out, width) // biWidth
  243. 243● write_u32_le(out, height * 2) // biHeight = 2*h (XOR + AND)
  244. 244● write_u16_le(out, 1) // biPlanes
  245. 245● write_u16_le(out, 32) // biBitCount
  246. 246● write_u32_le(out, 0) // biCompression = BI_RGB
  247. 247 let xor_size = width * height * 4
  248. 248● write_u32_le(out, xor_size) // biSizeImage
  249. 249● write_u32_le(out, 0) // biXPelsPerMeter
  250. 250● write_u32_le(out, 0) // biYPelsPerMeter
  251. 251● write_u32_le(out, 0) // biClrUsed
  252. 252● write_u32_le(out, 0) // biClrImportant
  253. 253 // XOR 掩码:32-bit BGRA,自下而上
  254. 254 for y in 0..<height {
  255. 255● let ry = height - 1 - y
  256. 256 let row_start = ry * width * channels
  257. 257 for x in 0..<width {
  258. 258● let idx = row_start + x * channels
  259. 259● let r = data[idx].to_int()
  260. 260◐ let g = if channels >= 2 { data[idx + 1].to_int() } else { r }
  261. 261◐ let b = if channels >= 3 { data[idx + 2].to_int() } else { r }
  262. 262● let a = if channels >= 4 { data[idx + 3].to_int() } else { 255 }
  263. 263● out.push(b.to_byte())
  264. 264● out.push(g.to_byte())
  265. 265● out.push(r.to_byte())
  266. 266● out.push(a.to_byte())
  267. 267 }
  268. 268 }
  269. 269 // AND 掩码:1-bit/pixel,自下而上,每行 4 字节对齐
  270. 270 let and_row_bytes = (width + 31) / 32 * 4
  271. 271 for y in 0..<height {
  272. 272● let ry = height - 1 - y
  273. 273 let row_start = ry * width * channels
  274. 274● let and_row : Array[Byte] = Array::make(and_row_bytes, b'\x00')
  275. 275 for x in 0..<width {
  276. 276● let idx = row_start + x * channels
  277. 277● let a = if channels >= 4 { data[idx + 3].to_int() } else { 255 }
  278. 278 // 透明像素 AND 掩码位置 1,不透明位置 0
  279. 279 if a == 0 {
  280. 280● let byte_idx = x / 8
  281. 281 let bit_idx = 7 - x % 8
  282. 282● and_row[byte_idx] = (and_row[byte_idx].to_int() | (1 << bit_idx)).to_byte()
  283. 283 }
  284. 284 }
  285. 285 for i in 0..<and_row_bytes {
  286. 286● out.push(and_row[i])
  287. 287 }
  288. 288 }
  289. 289 (out, width, height)
  290. 290}
  291. 291
  292. 292///|
  293. 293/// 将单个 Image 编码为 ICO 字节流(内嵌 32-bit BMP 子图像)
  294. 294pub fn encode_ico_pure(img : @types.Image) -> Bytes {
  295. 295● encode_ico_with_sizes_pure([img])
  296. 296}
  297. 297
  298. 298///|
  299. 299/// 将多个尺寸的 Image 编码为多分辨率 ICO 字节流
  300. 300pub fn encode_ico_with_sizes_pure(images : Array[@types.Image]) -> Bytes {
  301. 301● let count = images.length()
  302. 302 let out : Array[Byte] = []
  303. 303 // ICONDIR (6 bytes)
  304. 304● write_u16_le(out, 0) // reserved
  305. 305● write_u16_le(out, 1) // type = ICO
  306. 306● write_u16_le(out, count)
  307. 307 // 先编码所有子图像,收集偏移和大小
  308. 308 let subimages : Array[(Array[Byte], Int32, Int32)] = []
  309. 309 for i in 0..<count {
  310. 310● subimages.push(encode_ico_bmp_subimage(images[i]))
  311. 311 }
  312. 312 // 计算偏移:6 + count*16
  313. 313 let dir_size = 6 + count * 16
  314. 314 let mut offset = dir_size
  315. 315 // 写入目录条目
  316. 316 for i in 0..<count {
  317. 317● let (sub, w, h) = subimages[i]
  318. 318● let byte_size = sub.length()
  319. 319 // ICONDIRENTRY (16 bytes)
  320. 320● out.push((if w == 256 { 0 } else { w }).to_byte()) // width
  321. 321● out.push((if h == 256 { 0 } else { h }).to_byte()) // height
  322. 322● out.push(b'\x00') // colors (0 for >256 colors)
  323. 323● out.push(b'\x00') // reserved
  324. 324● write_u16_le(out, 1) // planes
  325. 325● write_u16_le(out, 32) // bit count
  326. 326● write_u32_le(out, byte_size)
  327. 327● write_u32_le(out, offset)
  328. 328 offset += byte_size
  329. 329 }
  330. 330 // 写入子图像数据
  331. 331 for i in 0..<count {
  332. 332● let (sub, _, _) = subimages[i]
  333. 333● for j in 0..<sub.length() {
  334. 334● out.push(sub[j])
  335. 335 }
  336. 336 }
  337. 337● Bytes::from_array(out)
  338. 338}
  339. 339
  340. 340///|
  341. 341/// 将单个 Image 编码为 CUR 字节流(内嵌 32-bit BMP 子图像,热点默认为中心)
  342. 342pub fn encode_cur_pure(img : @types.Image) -> Bytes {
  343. 343● encode_cur_with_hotspot_pure(img, img.width / 2, img.height / 2)
  344. 344}
  345. 345
  346. 346///|
  347. 347/// 将单个 Image 编码为 CUR 字节流,指定热点坐标
  348. 348pub fn encode_cur_with_hotspot_pure(
  349. 349 img : @types.Image,
  350. 350 hotspot_x : Int32,
  351. 351 hotspot_y : Int32,
  352. 352) -> Bytes {
  353. 353● let out : Array[Byte] = []
  354. 354 // ICONDIR (6 bytes)
  355. 355● write_u16_le(out, 0) // reserved
  356. 356● write_u16_le(out, 2) // type = CUR
  357. 357● write_u16_le(out, 1) // count
  358. 358 // 编码子图像
  359. 359● let (sub, w, h) = encode_ico_bmp_subimage(img)
  360. 360● let byte_size = sub.length()
  361. 361 let offset = 6 + 16
  362. 362 // ICONDIRENTRY (16 bytes)
  363. 363◐ out.push((if w == 256 { 0 } else { w }).to_byte())
  364. 364◐ out.push((if h == 256 { 0 } else { h }).to_byte())
  365. 365● out.push(b'\x00') // colors
  366. 366● out.push(b'\x00') // reserved
  367. 367● write_u16_le(out, hotspot_x) // 热点 X
  368. 368● write_u16_le(out, hotspot_y) // 热点 Y
  369. 369● write_u32_le(out, byte_size)
  370. 370● write_u32_le(out, offset)
  371. 371 // 子图像数据
  372. 372● for i in 0..<sub.length() {
  373. 373● out.push(sub[i])
  374. 374 }
  375. 375● Bytes::from_array(out)
  376. 376}