Electron截图实现的思路

您所在的位置:网站首页 c实现截图功能 Electron截图实现的思路

Electron截图实现的思路

2023-03-13 19:23| 来源: 网络整理| 查看: 265

Electron上截图的实现方案方案1 使用Electron提供的API 新建一个BrowserWindow; 在窗口加载完成,调用desktopCapturer获取缩略图 在窗口绘制两个canvas,一个用于遮罩,一个用于显示裁剪区域

附一下desktopCapturer的使用:

123456789101112131415161718192021222324jieping() { let that = this; let display = screen.getPrimaryDisplay(); let scaleFactor = display.scaleFactor; logger.log("scaleFactor:", display.bounds.width * scaleFactor); logger.log("height:", display.bounds.height * scaleFactor); desktopCapturer .getSources({ types: ["screen"], thumbnailSize: { width: display.bounds.width * scaleFactor, height: display.bounds.height * scaleFactor, }, }) .then(async (sources) => { let selectSource = sources[0]; let imageurl = selectSource.thumbnail.toDataURL("image/png"); ipcRenderer.send("jiangping_image", imageurl); //第一次发送时窗口没创建 用localStorage传递 localStorage.setItem("jiangping_image", imageurl) });},

这种方案的效率还是偏低,在分辨率较高的电脑上能明显感受到延迟

方案2 调用系统方法Windows截图

官网http://www.nirsoft.net/utils/nircmd.html

链接:https://pan.baidu.com/s/1AyGNHN5XM5v08gjGx3y6Dw提取码:sytu

1nircmd.exe savescreenshot "d:\temp.png"

这种方法其实各种语言都可以使用。

把nircmd.exe放在项目根目录的extraResources文件夹下

1234const libPath = path.join(__dirname, 'extraResources', 'nircmd.exe');const execFileSync = require('child_process').execFileSync;execFileSync(libPath, ['savescreenshot', 'd:\\temp001.png']);

package.json中配置

12345678910111213{ "name": "mytest", "productName": "测试项目", "version": "1.3.8", "description": "", "main": "main.js", "build": { "asar": true, "extraResources": [ "./extraResources/**" ] }} Mac截图

mac的优化方案很简单,使用mac自带的命令screencapture -i

screencapture是mac自带的截图命令,有-i和-w两种模式,分别是自由截图和窗口截图;

screencapture -i filePath,指定要保存的路径

screencapture -i -x filePath,关闭截图完成后的提示音

方案3 利用NodeJS库截图

screenshot-desktop

node-desktop-screenshot

方案4 调用原生模块

在Electron项目中调用原生模块。研究的Electron成熟产品大多采用了这种方法,如eagle、bearychat等。这种方法还可以细分成三种:

调用native代码编译的.node文件 通过node-ffi、edge-atom-shell等模块,在nodejs中直接写C++代码调用dll

electron作为跨平台PC开发框架,其提供了众多原生API,但毕竟需求各异,很多时候,我们仍需要实现基于C的底层业务。electron提供了nodejs调用原生模块的解决方案:使用Node原生模块

配置好node-gyp的环境后,将c++代码暴露出供node调用的接口,修改biding.gyp。编译生成当前electron环境的addon模块,即.node文件。

1node-gyp rebuild --runtime=electron --target_arch=ia32 --target=1.7.11 --disturl=https://atom.io/download/atom-shell 方案5 调用exe

这是项目目前采用的方案,nodejs中通过child_process的execFile方法去执行exe文件,exe调用同级目录下的dll,调出截图工具。

1234567891011121314const libPath = path.join(__dirname, 'capture.exe').replace('app.asar', 'app.asar.unpacked');clipboard.clear();const exec = require('child_process').execFile;exec(libPath, (err, stdout, stderr) => { if (err) log.error('capture error', err); log.info('capture finished', clipboard.readImage().isEmpty()); const image = clipboard.readImage(); if (!image.isEmpty()) { // 传给UI层处理 }})

将exe和dll文件打包到app.asar.unpacked目录下,通过绝对路径去执行。exe和dll是网上找的的,调用并不复杂。

其他项目推荐

screenshot,一个利用微信截图dll的C#和python工具



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3