93 lines
2.9 KiB
JavaScript
93 lines
2.9 KiB
JavaScript
'use strict';
|
||
function dimensions(bytes) {
|
||
if (
|
||
bytes.length >= 24 &&
|
||
bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) &&
|
||
bytes.toString('ascii', 12, 16) === 'IHDR'
|
||
)
|
||
return {
|
||
width: bytes.readUInt32BE(16),
|
||
height: bytes.readUInt32BE(20),
|
||
mediaType: 'image/png',
|
||
};
|
||
if (bytes[0] === 255 && bytes[1] === 216) {
|
||
let at = 2;
|
||
while (at + 4 < bytes.length) {
|
||
if (bytes[at++] !== 255) throw Error('invalid');
|
||
while (bytes[at] === 255) at++;
|
||
const marker = bytes[at++];
|
||
if (marker === 217 || marker === 218) break;
|
||
if (marker === 1 || (marker >= 208 && marker <= 215)) continue;
|
||
const length = bytes.readUInt16BE(at);
|
||
if (length < 2 || at + length > bytes.length) throw Error('invalid');
|
||
if (
|
||
[192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker) &&
|
||
length >= 8
|
||
)
|
||
return {
|
||
width: bytes.readUInt16BE(at + 5),
|
||
height: bytes.readUInt16BE(at + 3),
|
||
mediaType: 'image/jpeg',
|
||
};
|
||
at += length;
|
||
}
|
||
}
|
||
throw Error('invalid');
|
||
}
|
||
(async () => {
|
||
try {
|
||
const chunks = [];
|
||
let size = 0;
|
||
for await (const c of process.stdin) {
|
||
size += c.length;
|
||
if (size > 2 * 1024 * 1024) throw Error('size');
|
||
chunks.push(c);
|
||
}
|
||
const bytes = Buffer.concat(chunks),
|
||
shape = dimensions(bytes);
|
||
if (
|
||
!shape.width ||
|
||
!shape.height ||
|
||
shape.width > 8192 ||
|
||
shape.height > 8192 ||
|
||
shape.width * shape.height > 16000000
|
||
)
|
||
throw Error('pixels');
|
||
const { loadImage, createCanvas } = require('@napi-rs/canvas'),
|
||
image = await loadImage(bytes),
|
||
scale = Math.min(1, 1600 / Math.max(shape.width, shape.height)),
|
||
width = Math.max(1, Math.round(shape.width * scale)),
|
||
height = Math.max(1, Math.round(shape.height * scale)),
|
||
canvas = createCanvas(width, height),
|
||
ctx = canvas.getContext('2d');
|
||
ctx.drawImage(image, 0, 0, width, height);
|
||
const normalized = canvas.toBuffer(
|
||
shape.mediaType,
|
||
shape.mediaType === 'image/jpeg' ? 85 : undefined,
|
||
);
|
||
if (normalized.length > 2 * 1024 * 1024) throw Error('size');
|
||
process.stdout.write(
|
||
JSON.stringify({
|
||
kind: 'image',
|
||
mediaType: shape.mediaType,
|
||
width,
|
||
height,
|
||
imageData: normalized.toString('base64'),
|
||
content: '图片附件(' + width + '×' + height + ')',
|
||
characters: 0,
|
||
}),
|
||
);
|
||
} catch (e) {
|
||
process.stdout.write(
|
||
JSON.stringify({
|
||
error:
|
||
e.message === 'pixels'
|
||
? '图片超过 8192 边长或 1600 万像素,请缩小后添加。'
|
||
: e.message === 'size'
|
||
? '图片超过 2 MB,请缩小后添加。'
|
||
: '图片内容无效;目前支持 PNG、JPEG。',
|
||
}),
|
||
);
|
||
}
|
||
})();
|