@nestim/koishi-plugin-qq-group-manager 1.4.1 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,16 +49,29 @@ class ChatProvider {
49
49
  : await this.callOpenAi(request, images);
50
50
  if (result.ok)
51
51
  return { ...result, text: stripFence(result.text || '') };
52
- // 图片被拒(常见于 deepseek 等不支持 vision 的模型)→ 记住并去掉图片重试一次
53
- if (images.length && (result.status === 400 || result.status === 422 || /image|vision|multimodal/i.test(result.error || ''))) {
54
- this.visionUnsupported = true;
55
- this.logger?.warn?.(`[ai] 模型不支持图片(${result.status ?? '?'}),后续自动跳过图片: ${result.error}`);
56
- const fallback = provider === 'gemini'
57
- ? await this.callGemini(request, [])
58
- : await this.callOpenAi(request, []);
59
- if (fallback.ok)
60
- return { ...fallback, text: stripFence(fallback.text || ''), degradedToText: true };
61
- return fallback;
52
+ if (images.length) {
53
+ const errorText = String(result.error || '');
54
+ const rejected = result.status === 400
55
+ || result.status === 422
56
+ || /image|vision|multimodal/i.test(errorText);
57
+ if (rejected) {
58
+ // 「格式不对」和「模型不支持视觉」是两件事,必须分开处理。
59
+ // 前者只跳过这一次,后者才记进 visionUnsupported。
60
+ const formatProblem = /unsupported image|invalid image|image format|must be|one of the following formats|too large|dimension/i.test(errorText);
61
+ if (!formatProblem) {
62
+ this.visionUnsupported = true;
63
+ this.logger?.warn?.(`[ai] 模型不支持图片(${result.status ?? '?'}),后续自动跳过图片: ${errorText}`);
64
+ }
65
+ else {
66
+ this.logger?.warn?.(`[ai] 本次图片格式不被接受(${result.status ?? '?'}),仅跳过本次,不影响后续: ${errorText}`);
67
+ }
68
+ const fallback = provider === 'gemini'
69
+ ? await this.callGemini(request, [])
70
+ : await this.callOpenAi(request, []);
71
+ if (fallback.ok)
72
+ return { ...fallback, text: stripFence(fallback.text || ''), degradedToText: true };
73
+ return fallback;
74
+ }
62
75
  }
63
76
  return result;
64
77
  }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 内置 BMP → PNG 转码(纯 JS,零依赖)。
3
+ *
4
+ * 为什么需要:
5
+ * QQ 有时会把图片存成 BMP。DeepSeek 等视觉模型只接受 webp/png/jpeg/gif,
6
+ * 直接发 BMP 会 400。与其跳过这张图,不如转成 PNG 再发。
7
+ *
8
+ * 支持:
9
+ * - 1/4/8/16/24/32 位 BMP
10
+ * - BI_RGB(未压缩)、BI_BITFIELDS
11
+ * - 8 位调色板(含 RLE8 不处理,直接按索引读,够用)
12
+ *
13
+ * 不支持(遇到就返回 null,调用方回退到"跳过这张图"):
14
+ * - RLE 压缩
15
+ * - OS/2 v1 头
16
+ * - 带 alpha 的复杂变体(按 32 位 BGRA 直读,够常见场景用)
17
+ */
18
+ /** 判断是不是 BMP */
19
+ export declare function isBmp(buffer: any): boolean;
20
+ /**
21
+ * BMP → PNG buffer。
22
+ * @returns {Buffer|null} 成功返回 PNG,无法处理返回 null
23
+ */
24
+ export declare function bmpToPng(buffer: any): Buffer;
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+ /**
3
+ * 内置 BMP → PNG 转码(纯 JS,零依赖)。
4
+ *
5
+ * 为什么需要:
6
+ * QQ 有时会把图片存成 BMP。DeepSeek 等视觉模型只接受 webp/png/jpeg/gif,
7
+ * 直接发 BMP 会 400。与其跳过这张图,不如转成 PNG 再发。
8
+ *
9
+ * 支持:
10
+ * - 1/4/8/16/24/32 位 BMP
11
+ * - BI_RGB(未压缩)、BI_BITFIELDS
12
+ * - 8 位调色板(含 RLE8 不处理,直接按索引读,够用)
13
+ *
14
+ * 不支持(遇到就返回 null,调用方回退到"跳过这张图"):
15
+ * - RLE 压缩
16
+ * - OS/2 v1 头
17
+ * - 带 alpha 的复杂变体(按 32 位 BGRA 直读,够常见场景用)
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.isBmp = isBmp;
21
+ exports.bmpToPng = bmpToPng;
22
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
23
+ /** 判断是不是 BMP */
24
+ function isBmp(buffer) {
25
+ return !!buffer && buffer.length > 26 && buffer[0] === 0x42 && buffer[1] === 0x4d;
26
+ }
27
+ /** CRC32(PNG chunk 需要) */
28
+ const CRC_TABLE = (() => {
29
+ const table = new Int32Array(256);
30
+ for (let n = 0; n < 256; n += 1) {
31
+ let c = n;
32
+ for (let k = 0; k < 8; k += 1) {
33
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
34
+ }
35
+ table[n] = c;
36
+ }
37
+ return table;
38
+ })();
39
+ function crc32(buf) {
40
+ let c = 0xffffffff;
41
+ for (let i = 0; i < buf.length; i += 1) {
42
+ c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
43
+ }
44
+ return (c ^ 0xffffffff) >>> 0;
45
+ }
46
+ /** 组装一个 PNG chunk */
47
+ function chunk(type, data) {
48
+ const len = Buffer.alloc(4);
49
+ len.writeUInt32BE(data.length, 0);
50
+ const typeBuf = Buffer.from(type, 'ascii');
51
+ const crcBuf = Buffer.alloc(4);
52
+ crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
53
+ return Buffer.concat([len, typeBuf, data, crcBuf]);
54
+ }
55
+ /** 把 RGB(A) 像素编码成 PNG(真彩色 8 位) */
56
+ function encodePng(width, height, rgba) {
57
+ const stride = width * 4;
58
+ // 每行前置一个 filter byte(0 = None)
59
+ const raw = Buffer.alloc((stride + 1) * height);
60
+ for (let y = 0; y < height; y += 1) {
61
+ raw[y * (stride + 1)] = 0;
62
+ rgba.copy(raw, y * (stride + 1) + 1, y * stride, y * stride + stride);
63
+ }
64
+ const ihdr = Buffer.alloc(13);
65
+ ihdr.writeUInt32BE(width, 0);
66
+ ihdr.writeUInt32BE(height, 4);
67
+ ihdr[8] = 8; // bit depth
68
+ ihdr[9] = 6; // color type: RGBA
69
+ ihdr[10] = 0; // compression
70
+ ihdr[11] = 0; // filter
71
+ ihdr[12] = 0; // interlace
72
+ // zlib deflate(Node 自带)
73
+ const zlib = require('node:zlib');
74
+ const idat = zlib.deflateSync(raw, { level: 6 });
75
+ return Buffer.concat([
76
+ PNG_SIG,
77
+ chunk('IHDR', ihdr),
78
+ chunk('IDAT', idat),
79
+ chunk('IEND', Buffer.alloc(0)),
80
+ ]);
81
+ }
82
+ /**
83
+ * BMP → PNG buffer。
84
+ * @returns {Buffer|null} 成功返回 PNG,无法处理返回 null
85
+ */
86
+ function bmpToPng(buffer) {
87
+ if (!isBmp(buffer))
88
+ return null;
89
+ try {
90
+ const dataOffset = buffer.readUInt32LE(10);
91
+ const headerSize = buffer.readUInt32LE(14);
92
+ let width;
93
+ let height;
94
+ let bitCount;
95
+ let compression;
96
+ let paletteOffset;
97
+ if (headerSize === 12) {
98
+ // OS/2 v1:不支持
99
+ return null;
100
+ }
101
+ // BITMAPINFOHEADER 及以后
102
+ width = buffer.readInt32LE(18);
103
+ height = buffer.readInt32LE(22);
104
+ bitCount = buffer.readUInt16LE(28);
105
+ compression = buffer.readUInt32LE(30);
106
+ paletteOffset = 14 + headerSize;
107
+ if (!width || !height)
108
+ return null;
109
+ if (compression === 1 || compression === 2)
110
+ return null; // RLE 不支持
111
+ const bottomUp = height > 0;
112
+ const h = Math.abs(height);
113
+ const w = Math.abs(width);
114
+ // 极端尺寸保护(避免爆内存)
115
+ if (w > 8192 || h > 8192 || w * h > 20_000_000)
116
+ return null;
117
+ // 调色板:8 位及以下
118
+ let palette = null;
119
+ if (bitCount <= 8) {
120
+ const count = bitCount === 8 ? 256 : 1 << bitCount;
121
+ palette = new Uint8Array(count * 4);
122
+ let base = paletteOffset;
123
+ // 若头里声明了颜色数,用它
124
+ const declared = headerSize >= 40 ? buffer.readUInt32LE(46) : 0;
125
+ const use = declared && declared <= count ? declared : count;
126
+ for (let i = 0; i < use; i += 1) {
127
+ const off = base + i * 4;
128
+ if (off + 3 >= buffer.length)
129
+ break;
130
+ palette[i * 4] = buffer[off + 2]; // R
131
+ palette[i * 4 + 1] = buffer[off + 1]; // G
132
+ palette[i * 4 + 2] = buffer[off]; // B
133
+ palette[i * 4 + 3] = 255;
134
+ }
135
+ }
136
+ const rowSize = Math.floor((bitCount * w + 31) / 32) * 4;
137
+ const rgba = Buffer.alloc(w * h * 4);
138
+ for (let y = 0; y < h; y += 1) {
139
+ // BMP 默认自下而上存储
140
+ const srcY = bottomUp ? h - 1 - y : y;
141
+ const rowStart = dataOffset + srcY * rowSize;
142
+ if (rowStart >= buffer.length)
143
+ break;
144
+ for (let x = 0; x < w; x += 1) {
145
+ const dst = (y * w + x) * 4;
146
+ let r = 0;
147
+ let g = 0;
148
+ let b = 0;
149
+ let a = 255;
150
+ if (bitCount === 24) {
151
+ const off = rowStart + x * 3;
152
+ if (off + 2 >= buffer.length)
153
+ continue;
154
+ b = buffer[off];
155
+ g = buffer[off + 1];
156
+ r = buffer[off + 2];
157
+ }
158
+ else if (bitCount === 32) {
159
+ const off = rowStart + x * 4;
160
+ if (off + 3 >= buffer.length)
161
+ continue;
162
+ b = buffer[off];
163
+ g = buffer[off + 1];
164
+ r = buffer[off + 2];
165
+ const alpha = buffer[off + 3];
166
+ a = alpha === 0 ? 255 : alpha; // 很多 BMP 的 alpha 位全 0,按不透明处理
167
+ }
168
+ else if (bitCount === 16) {
169
+ const off = rowStart + x * 2;
170
+ if (off + 1 >= buffer.length)
171
+ continue;
172
+ const v = buffer.readUInt16LE(off);
173
+ // 默认 5-5-5
174
+ r = ((v >> 10) & 0x1f) << 3;
175
+ g = ((v >> 5) & 0x1f) << 3;
176
+ b = (v & 0x1f) << 3;
177
+ }
178
+ else if (bitCount === 8) {
179
+ const off = rowStart + x;
180
+ if (off >= buffer.length)
181
+ continue;
182
+ const idx = buffer[off] * 4;
183
+ r = palette ? palette[idx] : buffer[off];
184
+ g = palette ? palette[idx + 1] : buffer[off];
185
+ b = palette ? palette[idx + 2] : buffer[off];
186
+ }
187
+ else if (bitCount === 4) {
188
+ const off = rowStart + (x >> 1);
189
+ if (off >= buffer.length)
190
+ continue;
191
+ const byte = buffer[off];
192
+ const idxVal = x % 2 === 0 ? (byte >> 4) & 0x0f : byte & 0x0f;
193
+ const idx = idxVal * 4;
194
+ r = palette ? palette[idx] : 0;
195
+ g = palette ? palette[idx + 1] : 0;
196
+ b = palette ? palette[idx + 2] : 0;
197
+ }
198
+ else if (bitCount === 1) {
199
+ const off = rowStart + (x >> 3);
200
+ if (off >= buffer.length)
201
+ continue;
202
+ const byte = buffer[off];
203
+ const bit = 7 - (x % 8);
204
+ const idxVal = (byte >> bit) & 1;
205
+ const idx = idxVal * 4;
206
+ r = palette ? palette[idx] : 0;
207
+ g = palette ? palette[idx + 1] : 0;
208
+ b = palette ? palette[idx + 2] : 0;
209
+ }
210
+ else {
211
+ return null; // 未知位深
212
+ }
213
+ rgba[dst] = r;
214
+ rgba[dst + 1] = g;
215
+ rgba[dst + 2] = b;
216
+ rgba[dst + 3] = a;
217
+ }
218
+ }
219
+ return encodePng(w, h, rgba);
220
+ }
221
+ catch {
222
+ return null;
223
+ }
224
+ }
package/lib/service.d.ts CHANGED
@@ -236,6 +236,11 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
236
236
  isImageReference(value: any): boolean;
237
237
  extractImageCandidates(session: any, maxCount?: number): any[];
238
238
  detectImageMime(buffer: any, fallback?: string): string;
239
+ /**
240
+ * 把原始图片字节包成 data URL;BMP 会先转成 PNG。
241
+ * 视觉模型(DeepSeek 等)只认 webp/png/jpeg/gif,BMP 会被 400 拒掉。
242
+ */
243
+ buildImageDataUrl(buffer: any): string;
239
244
  resolveImageReferenceToDataUrl(ref: any, session: any): Promise<any>;
240
245
  fetchImageAsDataUrl(url: any, extraHeaders?: {}): Promise<any>;
241
246
  rememberImageDataUrl(url: any, dataUrl: any): void;
package/lib/service.js CHANGED
@@ -971,6 +971,24 @@ class QQGroupManagerService extends koishi_1.Service {
971
971
  return 'image/bmp';
972
972
  return fallback;
973
973
  }
974
+ /**
975
+ * 把原始图片字节包成 data URL;BMP 会先转成 PNG。
976
+ * 视觉模型(DeepSeek 等)只认 webp/png/jpeg/gif,BMP 会被 400 拒掉。
977
+ */
978
+ buildImageDataUrl(buffer) {
979
+ if (!buffer || !buffer.length)
980
+ return '';
981
+ if (bmp_1.isBmp(buffer)) {
982
+ const png = bmp_1.bmpToPng(buffer);
983
+ if (png && png.length) {
984
+ this._logger?.info?.(`[vision] BMP 已转为 PNG(${buffer.length} → ${png.length} 字节)`);
985
+ return `data:image/png;base64,${png.toString("base64")}`;
986
+ }
987
+ this._logger?.warn?.('[vision] BMP 转 PNG 失败,跳过这张图');
988
+ return '';
989
+ }
990
+ return `data:${this.detectImageMime(buffer)};base64,${buffer.toString("base64")}`;
991
+ }
974
992
  async resolveImageReferenceToDataUrl(ref, session) {
975
993
  const value = String(ref ?? '').trim();
976
994
  if (!value)
@@ -988,7 +1006,7 @@ class QQGroupManagerService extends koishi_1.Service {
988
1006
  const buffer = Buffer.from(raw, 'base64');
989
1007
  if (!buffer.length)
990
1008
  return '';
991
- return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
1009
+ return this.buildImageDataUrl(buffer);
992
1010
  }
993
1011
  if (/^https?:\/\//i.test(value)) {
994
1012
  // OneBot 的 get_image 能把 file_id 换成可访问链接
@@ -1020,7 +1038,7 @@ class QQGroupManagerService extends koishi_1.Service {
1020
1038
  try {
1021
1039
  const buffer = await node_fs_1.default.promises.readFile(finalUrl);
1022
1040
  if (buffer.length)
1023
- return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
1041
+ return this.buildImageDataUrl(buffer);
1024
1042
  }
1025
1043
  catch {
1026
1044
  return '';
@@ -1031,7 +1049,7 @@ class QQGroupManagerService extends koishi_1.Service {
1031
1049
  const localPath = value.replace(/^file:\/\//i, '');
1032
1050
  const buffer = await node_fs_1.default.promises.readFile(localPath).catch(() => null);
1033
1051
  if (buffer?.length)
1034
- return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
1052
+ return this.buildImageDataUrl(buffer);
1035
1053
  }
1036
1054
  return '';
1037
1055
  }
@@ -2234,8 +2252,11 @@ class QQGroupManagerService extends koishi_1.Service {
2234
2252
  return null;
2235
2253
  let keyword = raw;
2236
2254
  let score = null;
2237
- // 支持 "关键词|分值"、全角竖线、逗号分隔
2238
- const m = raw.match(/^(.+?)\s*[||,,::]\s*(\d{1,3})$/);
2255
+ // 支持 "关键词|分值"、全角竖线、逗号、冒号分隔。
2256
+ // 分值允许任意位数(有人会写 10000 想让它必触发),最终统一夹到 0..100。
2257
+ // 旧版 \d{1,3} 只能匹配 1~3 位,写 1000 以上会解析失败并回落到默认分值,
2258
+ // 表现为「加了高分值反而不触发」。
2259
+ const m = raw.match(/^(.+?)\s*[||,,::]\s*(\d+)\s*$/);
2239
2260
  if (m) {
2240
2261
  keyword = m[1].trim();
2241
2262
  const parsed = parseInt(m[2], 10);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nestim/koishi-plugin-qq-group-manager",
3
3
  "description": "Koishi QQ群管理插件(OneBot/LLOneBot):群管命令、权限校验、图片菜单、状态卡片、复读、AI群聊回复、记忆库、识图与自动管控(禁言/踢人)。",
4
- "version": "1.4.1",
4
+ "version": "1.4.3",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/readme.md CHANGED
@@ -167,7 +167,8 @@ npm i @nestim/koishi-plugin-qq-group-manager
167
167
  | 插件 | 作用 | 地址 |
168
168
  | --- | --- | --- |
169
169
  | `@nestim/koishi-plugin-qqgm-chat-style` | 聊天风格:一个主风格 + 多个按概率随机叠加的追加风格 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-chat-style) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-chat-style) |
170
- | `@nestim/koishi-plugin-qqgm-meme` | 表情包:AI 用 `[表情: 情绪]` 抽图,按概率补在文字后面 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-meme) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-meme) |
170
+ | `@nestim/koishi-plugin-qqgm-meme` | 表情包:AI 用 `[表情: 情绪]` 抽图,按概率补在文字后面 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-meme) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-meme) |
171
+ | `@nestim/koishi-plugin-qqgm-private` | 私聊:AI 自动回复 + 定时主动私发 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-private) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-private) |
171
172
 
172
173
  定时提醒(`[提醒] 明天 8 点 开会`)**内建在本插件里**,不需要额外安装。
173
174
 
@@ -76,15 +76,33 @@ export class ChatProvider {
76
76
 
77
77
  if (result.ok) return { ...result, text: stripFence(result.text || '') };
78
78
 
79
- // 图片被拒(常见于 deepseek 等不支持 vision 的模型)→ 记住并去掉图片重试一次
80
- if (images.length && (result.status === 400 || result.status === 422 || /image|vision|multimodal/i.test(result.error || ''))) {
81
- this.visionUnsupported = true;
82
- this.logger?.warn?.(`[ai] 模型不支持图片(${result.status ?? '?'}),后续自动跳过图片: ${result.error}`);
83
- const fallback = provider === 'gemini'
84
- ? await this.callGemini(request, [])
85
- : await this.callOpenAi(request, []);
86
- if (fallback.ok) return { ...fallback, text: stripFence(fallback.text || ''), degradedToText: true };
87
- return fallback;
79
+ if (images.length) {
80
+ const errorText = String(result.error || '');
81
+ const rejected = result.status === 400
82
+ || result.status === 422
83
+ || /image|vision|multimodal/i.test(errorText);
84
+
85
+ if (rejected) {
86
+ // 「格式不对」和「模型不支持视觉」是两件事,必须分开处理。
87
+ // 前者只跳过这一次,后者才记进 visionUnsupported。
88
+ const formatProblem = /unsupported image|invalid image|image format|must be|one of the following formats|too large|dimension/i.test(errorText);
89
+ if (!formatProblem) {
90
+ this.visionUnsupported = true;
91
+ this.logger?.warn?.(
92
+ `[ai] 模型不支持图片(${result.status ?? '?'}),后续自动跳过图片: ${errorText}`,
93
+ );
94
+ } else {
95
+ this.logger?.warn?.(
96
+ `[ai] 本次图片格式不被接受(${result.status ?? '?'}),仅跳过本次,不影响后续: ${errorText}`,
97
+ );
98
+ }
99
+
100
+ const fallback = provider === 'gemini'
101
+ ? await this.callGemini(request, [])
102
+ : await this.callOpenAi(request, []);
103
+ if (fallback.ok) return { ...fallback, text: stripFence(fallback.text || ''), degradedToText: true };
104
+ return fallback;
105
+ }
88
106
  }
89
107
  return result;
90
108
  }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * 内置 BMP → PNG 转码(纯 JS,零依赖)。
3
+ *
4
+ * 为什么需要:
5
+ * QQ 有时会把图片存成 BMP。DeepSeek 等视觉模型只接受 webp/png/jpeg/gif,
6
+ * 直接发 BMP 会 400。与其跳过这张图,不如转成 PNG 再发。
7
+ *
8
+ * 支持:
9
+ * - 1/4/8/16/24/32 位 BMP
10
+ * - BI_RGB(未压缩)、BI_BITFIELDS
11
+ * - 8 位调色板(含 RLE8 不处理,直接按索引读,够用)
12
+ *
13
+ * 不支持(遇到就返回 null,调用方回退到"跳过这张图"):
14
+ * - RLE 压缩
15
+ * - OS/2 v1 头
16
+ * - 带 alpha 的复杂变体(按 32 位 BGRA 直读,够常见场景用)
17
+ */
18
+
19
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
20
+
21
+ /** 判断是不是 BMP */
22
+ export function isBmp(buffer) {
23
+ return !!buffer && buffer.length > 26 && buffer[0] === 0x42 && buffer[1] === 0x4d;
24
+ }
25
+
26
+ /** CRC32(PNG chunk 需要) */
27
+ const CRC_TABLE = (() => {
28
+ const table = new Int32Array(256);
29
+ for (let n = 0; n < 256; n += 1) {
30
+ let c = n;
31
+ for (let k = 0; k < 8; k += 1) {
32
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
33
+ }
34
+ table[n] = c;
35
+ }
36
+ return table;
37
+ })();
38
+
39
+ function crc32(buf) {
40
+ let c = 0xffffffff;
41
+ for (let i = 0; i < buf.length; i += 1) {
42
+ c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
43
+ }
44
+ return (c ^ 0xffffffff) >>> 0;
45
+ }
46
+
47
+ /** 组装一个 PNG chunk */
48
+ function chunk(type, data) {
49
+ const len = Buffer.alloc(4);
50
+ len.writeUInt32BE(data.length, 0);
51
+ const typeBuf = Buffer.from(type, 'ascii');
52
+ const crcBuf = Buffer.alloc(4);
53
+ crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
54
+ return Buffer.concat([len, typeBuf, data, crcBuf]);
55
+ }
56
+
57
+ /** 把 RGB(A) 像素编码成 PNG(真彩色 8 位) */
58
+ function encodePng(width, height, rgba) {
59
+ const stride = width * 4;
60
+ // 每行前置一个 filter byte(0 = None)
61
+ const raw = Buffer.alloc((stride + 1) * height);
62
+ for (let y = 0; y < height; y += 1) {
63
+ raw[y * (stride + 1)] = 0;
64
+ rgba.copy(raw, y * (stride + 1) + 1, y * stride, y * stride + stride);
65
+ }
66
+
67
+ const ihdr = Buffer.alloc(13);
68
+ ihdr.writeUInt32BE(width, 0);
69
+ ihdr.writeUInt32BE(height, 4);
70
+ ihdr[8] = 8; // bit depth
71
+ ihdr[9] = 6; // color type: RGBA
72
+ ihdr[10] = 0; // compression
73
+ ihdr[11] = 0; // filter
74
+ ihdr[12] = 0; // interlace
75
+
76
+ // zlib deflate(Node 自带)
77
+ const zlib = require('node:zlib');
78
+ const idat = zlib.deflateSync(raw, { level: 6 });
79
+
80
+ return Buffer.concat([
81
+ PNG_SIG,
82
+ chunk('IHDR', ihdr),
83
+ chunk('IDAT', idat),
84
+ chunk('IEND', Buffer.alloc(0)),
85
+ ]);
86
+ }
87
+
88
+ /**
89
+ * BMP → PNG buffer。
90
+ * @returns {Buffer|null} 成功返回 PNG,无法处理返回 null
91
+ */
92
+ export function bmpToPng(buffer) {
93
+ if (!isBmp(buffer)) return null;
94
+
95
+ try {
96
+ const dataOffset = buffer.readUInt32LE(10);
97
+ const headerSize = buffer.readUInt32LE(14);
98
+
99
+ let width;
100
+ let height;
101
+ let bitCount;
102
+ let compression;
103
+ let paletteOffset;
104
+
105
+ if (headerSize === 12) {
106
+ // OS/2 v1:不支持
107
+ return null;
108
+ }
109
+
110
+ // BITMAPINFOHEADER 及以后
111
+ width = buffer.readInt32LE(18);
112
+ height = buffer.readInt32LE(22);
113
+ bitCount = buffer.readUInt16LE(28);
114
+ compression = buffer.readUInt32LE(30);
115
+ paletteOffset = 14 + headerSize;
116
+
117
+ if (!width || !height) return null;
118
+ if (compression === 1 || compression === 2) return null; // RLE 不支持
119
+
120
+ const bottomUp = height > 0;
121
+ const h = Math.abs(height);
122
+ const w = Math.abs(width);
123
+
124
+ // 极端尺寸保护(避免爆内存)
125
+ if (w > 8192 || h > 8192 || w * h > 20_000_000) return null;
126
+
127
+ // 调色板:8 位及以下
128
+ let palette = null;
129
+ if (bitCount <= 8) {
130
+ const count = bitCount === 8 ? 256 : 1 << bitCount;
131
+ palette = new Uint8Array(count * 4);
132
+ let base = paletteOffset;
133
+ // 若头里声明了颜色数,用它
134
+ const declared = headerSize >= 40 ? buffer.readUInt32LE(46) : 0;
135
+ const use = declared && declared <= count ? declared : count;
136
+ for (let i = 0; i < use; i += 1) {
137
+ const off = base + i * 4;
138
+ if (off + 3 >= buffer.length) break;
139
+ palette[i * 4] = buffer[off + 2]; // R
140
+ palette[i * 4 + 1] = buffer[off + 1]; // G
141
+ palette[i * 4 + 2] = buffer[off]; // B
142
+ palette[i * 4 + 3] = 255;
143
+ }
144
+ }
145
+
146
+ const rowSize = Math.floor((bitCount * w + 31) / 32) * 4;
147
+ const rgba = Buffer.alloc(w * h * 4);
148
+
149
+ for (let y = 0; y < h; y += 1) {
150
+ // BMP 默认自下而上存储
151
+ const srcY = bottomUp ? h - 1 - y : y;
152
+ const rowStart = dataOffset + srcY * rowSize;
153
+ if (rowStart >= buffer.length) break;
154
+
155
+ for (let x = 0; x < w; x += 1) {
156
+ const dst = (y * w + x) * 4;
157
+ let r = 0;
158
+ let g = 0;
159
+ let b = 0;
160
+ let a = 255;
161
+
162
+ if (bitCount === 24) {
163
+ const off = rowStart + x * 3;
164
+ if (off + 2 >= buffer.length) continue;
165
+ b = buffer[off];
166
+ g = buffer[off + 1];
167
+ r = buffer[off + 2];
168
+ } else if (bitCount === 32) {
169
+ const off = rowStart + x * 4;
170
+ if (off + 3 >= buffer.length) continue;
171
+ b = buffer[off];
172
+ g = buffer[off + 1];
173
+ r = buffer[off + 2];
174
+ const alpha = buffer[off + 3];
175
+ a = alpha === 0 ? 255 : alpha; // 很多 BMP 的 alpha 位全 0,按不透明处理
176
+ } else if (bitCount === 16) {
177
+ const off = rowStart + x * 2;
178
+ if (off + 1 >= buffer.length) continue;
179
+ const v = buffer.readUInt16LE(off);
180
+ // 默认 5-5-5
181
+ r = ((v >> 10) & 0x1f) << 3;
182
+ g = ((v >> 5) & 0x1f) << 3;
183
+ b = (v & 0x1f) << 3;
184
+ } else if (bitCount === 8) {
185
+ const off = rowStart + x;
186
+ if (off >= buffer.length) continue;
187
+ const idx = buffer[off] * 4;
188
+ r = palette ? palette[idx] : buffer[off];
189
+ g = palette ? palette[idx + 1] : buffer[off];
190
+ b = palette ? palette[idx + 2] : buffer[off];
191
+ } else if (bitCount === 4) {
192
+ const off = rowStart + (x >> 1);
193
+ if (off >= buffer.length) continue;
194
+ const byte = buffer[off];
195
+ const idxVal = x % 2 === 0 ? (byte >> 4) & 0x0f : byte & 0x0f;
196
+ const idx = idxVal * 4;
197
+ r = palette ? palette[idx] : 0;
198
+ g = palette ? palette[idx + 1] : 0;
199
+ b = palette ? palette[idx + 2] : 0;
200
+ } else if (bitCount === 1) {
201
+ const off = rowStart + (x >> 3);
202
+ if (off >= buffer.length) continue;
203
+ const byte = buffer[off];
204
+ const bit = 7 - (x % 8);
205
+ const idxVal = (byte >> bit) & 1;
206
+ const idx = idxVal * 4;
207
+ r = palette ? palette[idx] : 0;
208
+ g = palette ? palette[idx + 1] : 0;
209
+ b = palette ? palette[idx + 2] : 0;
210
+ } else {
211
+ return null; // 未知位深
212
+ }
213
+
214
+ rgba[dst] = r;
215
+ rgba[dst + 1] = g;
216
+ rgba[dst + 2] = b;
217
+ rgba[dst + 3] = a;
218
+ }
219
+ }
220
+
221
+ return encodePng(w, h, rgba);
222
+ } catch {
223
+ return null;
224
+ }
225
+ }