跳到主要内容

RobotJS截取屏幕screen.capture踩坑

1 分钟阅读

起因

调用 robot.screen.capture() 或 robot.screen.capture(0,0,1920,1080),返回的Bitmap对象是色彩格式是BGR色彩,这导致了如果未经处理就直接生成图像,色彩会产生错误,

处理方法

只需将BGR色彩转换成RGB色彩即可。

const robot = require('robotjs');
const jimp = require("jimp");

const swapRedAndBlueChannel = bmp => {
for (let i = 0; i < (bmp.width * bmp.height) * 4; i += 4) { // swap red and blue channel
[bmp.image[i], bmp.image[i + 2]] = [bmp.image[i + 2], bmp.image[i]]; // red channel;
}
};

const screenshot = robot.screen.capture();
swapRedAndBlueChannel(screenshot);
const screenJimp = new jimp({ data: screenshot.image, width: screenshot.width, height: screenshot.height });

screenJimp.write('screenshot.png');

如果你有使用OpenCV,则可以使用“COLOR_BGR2RGB”函数直接转换

const cv = require('@u4/opencv4nodejs');
const robot = require('robotjs');
const jimp = require("jimp");


const screenshot = robot.screen.capture();
const screenJimp = new jimp({ data: screenshot.image, width: screenshot.width, height: screenshot.height });

screenJimp.getBuffer(jimp.MIME_PNG, function (err, buffer) {
if (err) {
return;
}
const screen = cv.imdecode(Buffer.from(buffer)).cvtColor(cv.COLOR_BGR2RGB);
console.log(screen)
});
评论
0条评论

添加新评论

昵称
邮箱
网址