Repository navigation
Expand file tree
/
Copy pathpng-transcode.ts
More file actions
35 lines (31 loc) · 1.63 KB
/
Copy pathpng-transcode.ts
File metadata and controls
35 lines (31 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { AppError } from '@agent-device/kernel/errors';
import { decode as decodeJpeg } from 'jpeg-js';
import { PNG } from 'pngjs';
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const JPEG_SIGNATURE = Buffer.from([0xff, 0xd8, 0xff]);
export type ScreenshotImageFormat = 'png' | 'jpeg';
/** Names the container a screenshot arrived in from its magic bytes, or `undefined` for neither. */
export function detectScreenshotImageFormat(bytes: Buffer): ScreenshotImageFormat | undefined {
if (bytes.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) return 'png';
if (bytes.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)) return 'jpeg';
return undefined;
}
/**
* Returns PNG bytes for a screenshot a provider handed back in whatever container it prefers. PNG
* passes through untouched; JPEG is decoded and re-encoded losslessly from the decoded pixels, so
* every PNG-only reader downstream (size, crop, overlay, diff) sees the format the path promises.
*/
export function transcodeScreenshotToPng(bytes: Buffer, label: string): Buffer {
const format = detectScreenshotImageFormat(bytes);
if (format === 'png') return bytes;
if (format === 'jpeg') {
const decoded = decodeJpeg(bytes, { useTArray: true, formatAsRGBA: true });
const png = new PNG({ width: decoded.width, height: decoded.height });
png.data = Buffer.from(decoded.data.buffer, decoded.data.byteOffset, decoded.data.byteLength);
return PNG.sync.write(png);
}
throw new AppError('COMMAND_FAILED', `${label} is neither PNG nor JPEG`, {
label,
leadingBytes: bytes.subarray(0, 4).toString('hex'),
});
}