Electron:点击右键保存图片到本地

发布于:2025-03-08 ⋅ 阅读:(123) ⋅ 点赞:(0)

前期插件

前端请求后台的一种方法

npm install got -S

用于获取ArrayBuffer文件类型

npm install image-type -S

生成随机数

npm install randomstring -D

增加右击事件

点击右击事件的时候加载菜单

const imageRightSave = require("./ImageRightSave")  // 创建右击菜单
const imageSaveLocalUtil = require("../utils/ImageSaveLocalUtil");  // 保存图片到本地
let shortcutRegistered = false;  // 用于控制是否注册快捷键

// 监听右击事件
win.webContents.on('context-menu', (e, args) => {
  if (!args.srcURL) return  // 如果路由地址为空则不显示快捷键
  if (!shortcutRegistered) {
    globalShortcut.register("CommandOrControl+S", () => {
      imageSaveLocalUtil(args.srcURL)
    })
    shortcutRegistered = true
  }
  contextMenu = imageRightSave(args.srcURL)
  contextMenu.popup()

  contextMenu.on("menu-will-close", () => {
    globalShortcut.unregister("CommandOrControl+S")  // 注销快捷键
    shortcutRegistered = false
  })
})

编写菜单

注意:accelerator只负责显示快捷键,但是没有快捷键的功能,需要自己手动编写快捷键的规则。 切记 切记 切记!!!

const {Menu} = require('electron');
const imageSaveLocalUtil = require("../utils/ImageSaveLocalUtil")

const imageRightSave = (url) => {
  const template = [
    {
      label: "图片另存为...",
      accelerator: "CommandOrControl+S",  // 仅仅用于快捷键的显示,但是不会有快捷键的功能
      click: async () => {
        imageSaveLocalUtil(url)  // 保存图片到本地
      }
    }
  ]
  return Menu.buildFromTemplate(template)
}

module.exports = imageRightSave

保存本地

const {dialog} = require("electron");
const {default: got} = require("got");
const path = require("path");
const randomstring = require("randomstring");
const fs = require("fs");
const warningMessageUtil = require("./WarningMessageUtil");


/**
 * 加载文件类型
 * @param chunk
 */
async function loadFileType(chunk) {
  const imageType = (await import('image-type')).default;
  const imgType = await imageType(chunk)  // 现在您可以使用 imageType 了
  return imgType.ext;
}

/**
 * 将图片保存到本地
 */
const imageSaveLocalUtil = async (url) => {
  await got.get(url).then(async (res) => {
    const chunk = Buffer.from(res.rawBody);
    const suffix = await loadFileType(chunk)
    if (suffix == null || suffix == undefined || suffix == "") {
      warningMessageUtil("图片加载失败")
      return
    }
    const {filePath, canceled} = await dialog.showSaveDialog({
      title: '图片另存为',
      defaultPath: path.resolve(__dirname, '../../public/uploads/' + randomstring.generate(10) + "." + suffix),
    })
    if (canceled) return  // 用户点击了取消
    fs.writeFileSync(filePath, chunk)  // 数组写入本地
  }).catch((e) => {
    console.error(e)
  })
}

module.exports = imageSaveLocalUtil


警告消息提示

const {dialog, ipcMain} = require('electron');

const messagePrompt = (msg) => {
  dialog.showMessageBox({
    message: msg,
    type: 'warning',
  })
}

module.exports = messagePrompt