首页 > 解决方案 > 从本地磁盘加载图像

问题描述

我目前使用电子-vue 样板来接触电子。

我的目标是显示应用程序(渲染器进程)中给定文件夹中的所有图像。

<template>
  <div>
    <button @click="selectSourceDir()">Quellverzeichnis</button>
    Aktuell: {{sourcePath}}
    <button @click="scan()">Aktualisieren</button>
    <ul>
      <li v-for="image in images">
        <!--<img v-bind:src="'data:image/jpg;base64,' + image.base64">-->
        <img v-bind:src="'file://' + image.path">
      </li>
    </ul>
    
  </div>
</template>

<script>
  import ImageFile from './ImageDispatchPage/ImageFile';
  import fs from 'fs';
  import { ipcRenderer as ipc } from 'electron';
  import path from 'path';

  export default {
    name: 'image-dispatch-page',
    components: { ImageFile },
    data () {
      return{
        images: [],
        sourcePath: null,
      }  
    },
    methods: {     
      scan(){        
        // If path is not set do nothing
        if(!this.sourcePath){
          return;
        }
        // Iterate over all files in directory
        let files = fs.readdirSync(this.sourcePath);
        const regex = /.jpe?g$/gmi;        
        for (let file of files){          
          // Ignore non jpg files                    
          if(!file.match(regex)){
            continue;                                    
          }          
          let image = {};
          image.name = file;
          image.path = path.join(this.sourcePath, file);
          image.base64 = new Buffer(fs.readFileSync(image.path)).toString('base64');       
          this.images.push(image);
        }        
      },
      selectSourceDir(){
        ipc.send('open-directory-dialog');        
        ipc.on('selected-directory', (event, directory) => {
          this.sourcePath = directory;         
        });        
      }
    },
    created(){
      this.scan();
    } 
  }
</script>

<style scoped>
  
</style>

运行此代码会导致以下错误消息:错误 如果我将注释掉的行与非常慢的 base64 编码图像一起使用(第 8 行),则一切正常。

简单地显示这些图像的正确解决方案是什么?

标签: javascriptelectronelectron-vue

解决方案


在我的主要进程中关闭网络安全起到了作用。

mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
    webPreferences: {
        webSecurity: false
    }
});

推荐阅读