用电子从文件系统中选择并显示图像

rvr*_*rbk 5 javascript image file electron

我正在用Electron开发一个小应用程序,可以从该应用程序将图像上传到Instagram,但是我停留在第一步中:

我想从文件系统中选择一个图像并将其显示在我的应用程序中。

这是到目前为止我得到的代码:

码:

remote.dialog.showOpenDialog((filenames) => {
    fs.readFile(filepath, 'utf-8', (err, data) => {

        if(err){
            alert("An error ocurred reading the file :" + err.message);
            return;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

11A*_*ND2 9

一个选择,阅读和显示png图像的最小示例。

渲染过程:::

var remote = require('electron').remote;
var fs = remote.require('fs');

  
remote.dialog.showOpenDialog(remote.getCurrentWindow(),
   {
    filters: [
      {name: 'Images', extensions: ['png']}
    ]
   }, 
   function(filepaths, bookmarks) {
     //read image (note: use async in production)
     var _img = fs.readFileSync(filepaths[0]).toString('base64');
     //example for .png
     var _out = '<img src="data:image/png;base64,' + _img + '" />';
     //render/display
     var _target = document.getElementById('image_container');
     _target.insertAdjacentHTML('beforeend', _out);

     return;
});
Run Code Online (Sandbox Code Playgroud)
<div id="image_container"></div>
Run Code Online (Sandbox Code Playgroud)


小智 8

对于 Electron 11,以下来自https://www.electronjs.org/docs/api/protocol的代码片段 可以工作

app.whenReady().then(() => {
  protocol.registerFileProtocol('atom', (request, callback) => {
    console.log(request.url)
    const url = request.url.substr(7)
    callback({ path: url })
  })
})
Run Code Online (Sandbox Code Playgroud)

注意不要使用常用的file://协议,而是使用自定义的“atom”或“my_whatever”协议

您现在可以通过以下方式获取图像:

<img src="atom://C:\\Users\\my_path\\myfile.png" />
Run Code Online (Sandbox Code Playgroud)

但是,如果您不想file在渲染端保留协议的语法,您可以执行以下操作:

protocol.registerFileProtocol('file', ()=>...)
Run Code Online (Sandbox Code Playgroud)

现在你可以通过这种方式获取图像

<img src="file://C:\\Users\\my_path\\myfile.png" />
Run Code Online (Sandbox Code Playgroud)

但是您必须禁用webSecurity

const mainWindow = new BrowserWindow({
webPreferences: {
  nodeIntegration : true,
  webSecurity: false
}
Run Code Online (Sandbox Code Playgroud)


osh*_*ell 6

这是一个解决方案,其中包含有关main进程分离renderer和使用的更多信息es6

主进程

import { ipcMain, dialog } from "electron";
import fs from 'fs';

ipcMain.on("chooseFile", (event, arg) => {
  const result = dialog.showOpenDialog({
    properties: ["openFile"],
    filters: [{ name: "Images", extensions: ["png","jpg","jpeg"] }]
  });

  result.then(({canceled, filePaths, bookmarks}) => {
    const base64 = fs.readFileSync(filePaths[0]).toString('base64');
    event.reply("chosenFile", base64);
  });
});
Run Code Online (Sandbox Code Playgroud)

渲染器进程

import electron from 'electron';

// trigger file prompt
electron.ipcRenderer.send('chooseFile');

// handle response
electron.ipcRenderer.on('chosenFile', (event, base64) => {
  const src = `data:image/jpg;base64,${base64}`
})
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。这对我来说更加相关和容易理解 (2认同)