首页 > 解决方案 > Electron / Angular 保存 desktopCapturer 抓取的图像

问题描述

我有一些代码可以截取屏幕截图并将其存储在变量中。

这是代码:

takeScreenshot() {
    desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 800, height: 600 })
    .then( (sources: { thumbnail: { toDataURL: () => any; }; }[]) => {
      
      const theimage = sources[0].thumbnail.toDataURL(); // Thumbnail size image


    })
}

我现在想将此屏幕截图保存到我的计算机中。

我试过这个:

fs.writeFile('myimage.png', this.theimage, function(err: any) {
        if (err) {
            console.error('Failed to save ' + err);
        } else {
            console.log('Saved: ' + 'myimage.png');
        }
    });

但它创建的文件不会作为图像打开。

如何将此捕获保存为图像?

标签: javascriptangularelectron

解决方案


您可以contents.capturePage([dimensions])在主文件上使用。如果您不提供尺寸参数,它将捕获整个窗口。这将返回带有原生图像的承诺,您可以使用它fs.writeFile来创建新的图像文件。

样本

const {
  app,
  BrowserWindow
} = require('electron');
const fs = require('fs');

const initWindow = () => {
  const window = new BrowserWindow({
    width: 800,
    height: 600,
  });

  window.loadFile('index.html');
  return window;
}

app.once('ready', async () => {
  const window = initWindow();
  const image = await window.webContents.capturePage();
  fs.writeFile('image.png', image.toPNG());
});

推荐阅读