Open History to see the last commit
1import { deflateSync } from 'node:zlib'
2
3/** Raw screen pixels, as robotjs captures them: blue, green, red, then one unused byte. */
4export interface Bitmap {
5 width: number
6 height: number
7 /** Bytes in one row. */
8 byteWidth: number
9 bytesPerPixel: number
10 image: Uint8Array
11}
12
13const SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
14
15const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
16 let c = n
17 for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
18 return c >>> 0
19})
20
21// ponytail: zlib.crc32 needs Node 20.15. The package supports Node 18.
22function crc32(bytes: Uint8Array) {
23 let c = 0xffffffff
24 for (const byte of bytes) c = (CRC_TABLE[(c ^ byte) & 0xff] ?? 0) ^ (c >>> 8)
25 return (c ^ 0xffffffff) >>> 0
26}
27
28function chunk(type: string, data: Uint8Array) {
29 const out = Buffer.alloc(12 + data.length)
30 out.writeUInt32BE(data.length, 0)
31 out.write(type, 4, 'latin1')
32 out.set(data, 8)
33 out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length)
34 return out
35}
36
37/**
38 * Scale a bitmap to `width` x `height`, then encode it as an RGB PNG.
39 *
40 * Each output pixel is the average of the source pixels that it covers, so
41 * small text stays readable.
42 */
43export function toPng(bitmap: Bitmap, width: number, height: number) {
44 const { image, byteWidth, bytesPerPixel } = bitmap
45 const rowLength = 1 + width * 3
46 // Each row starts with filter byte 0, which Buffer.alloc already set.
47 const rows = Buffer.alloc(rowLength * height)
48
49 for (let ty = 0; ty < height; ty++) {
50 const y0 = Math.floor((ty * bitmap.height) / height)
51 const y1 = Math.max(y0 + 1, Math.floor(((ty + 1) * bitmap.height) / height))
52 for (let tx = 0; tx < width; tx++) {
53 const x0 = Math.floor((tx * bitmap.width) / width)
54 const x1 = Math.max(x0 + 1, Math.floor(((tx + 1) * bitmap.width) / width))
55 let red = 0
56 let green = 0
57 let blue = 0
58 for (let y = y0; y < y1; y++) {
59 for (let x = x0; x < x1; x++) {
60 const i = y * byteWidth + x * bytesPerPixel
61 blue += image[i] ?? 0
62 green += image[i + 1] ?? 0
63 red += image[i + 2] ?? 0
64 }
65 }
66 const count = (y1 - y0) * (x1 - x0)
67 const o = ty * rowLength + 1 + tx * 3
68 rows[o] = Math.round(red / count)
69 rows[o + 1] = Math.round(green / count)
70 rows[o + 2] = Math.round(blue / count)
71 }
72 }
73
74 const header = Buffer.alloc(13)
75 header.writeUInt32BE(width, 0)
76 header.writeUInt32BE(height, 4)
77 header[8] = 8 // 8 bits for each color
78 header[9] = 2 // RGB
79 return Buffer.concat([
80 SIGNATURE,
81 chunk('IHDR', header),
82 chunk('IDAT', deflateSync(rows)),
83 chunk('IEND', new Uint8Array()),
84 ])
85}