首页 > 解决方案 > 使用 Electron 截取桌面截图

问题描述

我正在使用 Electron 创建一个创建全屏透明覆盖窗口的 Windows 应用程序。此覆盖的目的是:

  1. 截取整个屏幕的屏幕截图(不是透明的覆盖层本身,而是屏幕“下方”),
  2. 通过将图像作为字节流发送到我的 python 服务器来处理这个图像,并且
  3. 在叠加层上画一些东西

我陷入了第一步,即屏幕截图捕获过程。

我尝试了选项 1,即使用capturePage()

this.electronService.remote.getCurrentWindow().webContents.capturePage()
    .then((img: Electron.NativeImage) => { ... }

但这仅捕获了我的覆盖窗口(而不是桌面屏幕)。这将是一个空白图像,对我来说毫无用处。

选项 2是使用desktopCapturer

this.electronService.remote.desktopCapturer.getSources({types: ['screen']}).then(sources => {
    for (const source of sources) {
        if (source.name === 'Screen 1') {
            try {
                const mediaDevices = navigator.mediaDevices as any;
                mediaDevices.getUserMedia({
                    audio: false,
                    video: { // this specification is only available for Chrome -> Electron runs on Chromium browser
                        mandatory: {
                            chromeMediaSource: 'desktop',
                            chromeMediaSourceId: source.id,
                            minWidth: 1280,
                            maxWidth: 1280,
                            minHeight: 720,
                            maxHeight: 720
                        }
                    }
                }).then((stream: MediaStream) => { // stream.getVideoTracks()[0] contains the video track I need
                    this.handleStream(stream);
                });
            } catch (e) {
            }
        }
    }
});

下一步是它对我来说变得模糊的地方。我该怎么做MediaStream才能从屏幕截图中获取字节流?我看到很多如何在网页上显示此流的示例,但我希望将其发送到我的后端。这个 StackOverflow 帖子提到了如何做到这一点,但我没有让它正常工作。这就是我实现的方式handleStream()

import * as MediaStreamRecorder from 'msr';

private handleStream(stream: MediaStream): void {
    recorder.stop()
    const recorder = new MediaStreamRecorder(stream);
    recorder.ondataavailable = (blob: Blob) => { // I immediately get a blob, while the linked SO page got an event and had to get a blob through event.data
        this.http.post<Result>('http://localhost:5050', blob);
    };

    // make data available event fire every one second
    recorder.start(1000);
}

blobPython 服务器不接受。检查内容后Blob,我怀疑这是一个视频。我用以下代码验证了这一点:

let url = URL.createObjectURL(blob);
window.open(url, '_blank')

在新窗口中打开 blob。它显示可能半秒的视频,但我想要一个静态图像。那么如何从中获取特定的快照呢?我也不确定是否只需在 POST 正文中发送 Javascript blob 格式就可以让 Python 正确解释它。在 Java 中,它通过简单地发送byte[]图像来工作,所以我验证了 Python 服务器实现按预期工作。

除了使用之外的任何建议desktopCapturer也很好。这个实现也捕获了我的鼠标,我宁愿没有。我必须承认,我没想到这个功能会这么难实现。

标签: javascriptangularelectron

解决方案


以下是截取桌面屏幕截图的方法:

const { desktopCapturer } = require('electron')

document.getElementById('screenshot-button').addEventListener('click', () => { // The button which takes the screenshot
    desktopCapturer.getSources({ types: ['screen'] })
        .then( sources => {
            document.getElementById('screenshot-image').src = sources[0].thumbnail.toDataURL() // The image to display the screenshot
        })
})

使用“屏幕”将截取整个桌面的屏幕截图。使用“windows”将只截取应用程序的屏幕截图。

另请参阅这些文档:https ://www.electronjs.org/docs/api/desktop-capturer


推荐阅读