1.创建窗口,加载页面,代码如下:
//打开窗口const {ipcMain, BrowserWindow} = require("electron")
const saveImage = require("../ipcMain/saveImage")
let win = null;
ipcMain.handle('on-open-event', (event, args) => {if (!win) {win = new BrowserWindow({width: 1200,height: 800,})win.setMenu(null)}win.loadURL("https://www.jingdong.com");win.webContents.on("context-menu", (event, args) => {event.preventDefault();//判断图片资源路径是否为空if (args.srcURL !== ""){saveImage(event,args.srcURL);}})win.on("closed", () => {win = null;})
})
2.封装图片保存方法,代码如下:
const {Menu, dialog, BrowserWindow, shell} = require("electron")
const path = require("path");
const got = require("got")
const imageType = require("image-type")
const randomString = require("randomstring");
const fs = require('fs')let menu = null;
const saveImage = (event, srcURL) => {if (!menu) {menu = Menu.buildFromTemplate([{label: "保存图片",click: async () => {try {const respones = await got(srcURL) //通过图片地址获取数据流const buffer = Buffer.from(respones.rawBody) //数据流转成Bufferconst ImageType = await imageType(buffer); //获取图片格式const fileName = randomString.generate(10);//随机生成10位由数字、字母组合的文件名let {canceled, filePath} = await dialog.showSaveDialog({title: "图片另存为",defaultPath: path.resolve(__dirname, '../public/uploads/' + fileName + '.' + ImageType.ext),})if (!canceled) {//写入图片数据fs.writeFileSync(filePath, buffer)//查看保存的图片资源dialog.showMessageBox({message: "保存成功",type: "info",buttons: ["查看"],noLink: false,}).then(res => {shell.openPath(path.resolve(__dirname, '../public/uploads/'))})}} catch (e) {console.log(e)}}}])}//显示菜单menu.popup()
}module.exports = saveImage
3.运行效果: