Generating and saving a thumbnail image

When we requested the capturing source, we provided a thumbnail size that's equal to the size of the main screen. Now you can use the NativeImage methods to perform any necessary image conversion and manipulation.

Many useful APIs are exposed by the NativeImage class. You can find out more at https://electronjs.org/docs/api/native-image#class-nativeimage.

For now, you need the following functions to finish the application:

  • toPNG: This converts image data into png format.
  • resize: This manipulates the size of the resulting image.
  • crop: This cuts out a portion of the image.

You can convert the screen thumbnail into a png image using the following code:

const image = entireScreenSource.thumbnail.toPNG();

Follow these steps to get started:

  1. First, let's import the os, path, and fs classes from Node.js so that we can generate temporary file names. Now, we need to use the writeFile function to store the file locally. We also need shell from Electron so that we can invoke shell commands:
      const { desktopCapturer, remote, shell } = 
window.require('electron');
const screen = remote.screen;
const path = window.require('path');
const os = window.require('os');
const fs = window.require('fs');
  1. Next, update your code so that it looks as follows. Here, we are generating a temporary file, saving the PNG image, and using shell.openExternal to launch the file outside the Electron shell:
      try {
const screenSize = screen.getPrimaryDisplay().workAreaSize;
const maxDimension = Math.max(screenSize.width,
screenSize.height);

const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: {
width: maxDimension * window.devicePixelRatio,
height: maxDimension * window.devicePixelRatio
}
});

const entireScreenSource = sources.find(
source => source.name === 'Entire Screen' || source.name ===
'Screen 1'
);

if (entireScreenSource) {
const outputPath = path.join(os.tmpdir(), 'screenshot.png');
const image = entireScreenSource.thumbnail.toPNG();

fs.writeFile(outputPath, image, err => {
if (err) return console.error(err);
shell.openExternal(`file://${outputPath}`);
});

}
} catch (err) {
console.error(err);
}
  1. Your operating system will automatically fetch the default application for previewing files. For macOS, for example, you should expect a standard preview to appear.
  2. Update the code so that it can handle the missing screen source:
      if (entireScreenSource) {
// ...
} else {
window.alert('Screen source not found.');
}

Now, let's look at how we can manipulate the resulting image. It's time to learn how to resize and crop the image.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.25.74