NodeJS从另一个窗口获取像素颜色

时间:2019-07-13 21:30:35

标签: javascript node.js windows

如何使用NodeJS访问屏幕上像素的颜色?

我的用例适用于Windows,但是跨平台的解决方案将是理想的选择。

以下是C#中的示例,可能会有所帮助:C# get pixel color from another window

1 个答案:

答案 0 :(得分:0)

我最终使用node-ffi将链接的C#答案转换为NodeJS:

import ffi from "ffi";
import chroma from "chroma-js";

var user32 = new ffi.Library("user32", {
    "GetDC": ["int32", ["int32"]],
    "ReleaseDC": ["int32", ["int32", "int32"]],
});
var gdi32 = new ffi.Library("gdi32", {
    "GetPixel": ["uint32", ["int32", "int32", "int32"]],
});

export function GetPixelColor(x: number, y: number) {
    let hdc = user32.GetDC(0);
    let pixel = gdi32.GetPixel(hdc, x, y);
    user32.ReleaseDC(0, hdc);
    let color = chroma(pixel & 0x000000FF, (pixel & 0x0000FF00) >> 8, (pixel & 0x00FF0000) >> 16);
    return color.hex().substr(1); // to match with robotjs.getPixelColor() returns
}

要使用:

let pixelColor = GetPixelColor(0, 0);
console.log("Color: #" + pixelColor);

选项2

另一种选择是使用robotjs软件包:https://github.com/octalmage/robotjs

警告:如果在打开UAC提示时调用getPixelColor,当前会导致崩溃。 (see issue