195 字
1 分钟
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)}); RobotJS截取屏幕screen.capture踩坑
https://fuwari.vercel.app/posts/2023年/robotjs截取屏幕screencapture踩坑/