简体   繁体   中英

How do I set a window icon to a Buffer image in Electron?

I have an image that is stored in a buffer. I'm trying to set it as the window icon, but I can't find a way to do so. There is no path to the image, so I can't just use win.setIcon('path/to/image') .

I tried to do the following, to no success.

win.setIcon(buffer); // giving the buffer by itself
win.setIcon(buffer.toString('base64')); // giving the buffer as base64
win.setIcon(`data:image/png;base64,${buffer.toString('base64')}`); // giving as base64 url

let imageObject = new Image();
imageObject.src = `data:image/png;base64,${buffer.toString('base64')}`;
win.setIcon(imageObject); // giving image object

According to Electron's documentation , BrowserWindow.setIcon () takes either a string or a NativeImage , a data type provided by Electron. You can convert your buffer to a NativeImage by using the following code:

const { nativeImage } = require ("electron");

win.setIcon (nativeImage.createFromBuffer (buffer));

If that does not help, you can also pass your buffer as a Base 64 string in a data URL (like you have tried before) to the function createFromDataURL . For more information, see the documentation on NativeImage . It is also worth noting that you can pass advanced options to the createFromBuffer function to give Electron more hints about how to display your icon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM