RobotJS截取屏幕screen.capture踩坑

调用 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)
});
posted @   摸鱼的云小逸  阅读(320)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示