I have some code that takes a screenshot and stores it in a variable.
Here is the code:
takeScreenshot() {
desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 800, height: 600 })
.then( (sources: { thumbnail: { toDataURL: () => any; }; }[]) => {
const theimage = sources[0].thumbnail.toDataURL(); // Thumbnail size image
})
}
I now want to save this screenshot into my computer.
I've tried this:
fs.writeFile('myimage.png', this.theimage, function(err: any) {
if (err) {
console.error('Failed to save ' + err);
} else {
console.log('Saved: ' + 'myimage.png');
}
});
But the file that it creates does not open as an image.
How can I save this capture as an image?
You can use contents.capturePage([dimensions]) on your main file. if you dont provide dimensions argument it will capture the whole window. This will return a promise with native image, and you can use fs.writeFile to create a new image file.
sample
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());
});