lasagne
lasagne

Reputation: 641

Load images from local disk

I currently get my hands on electron with the electron-vue boilerplate.

My goal is to show all images from a given folder in the application (renderer process).

<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>

Running this code results in the following error message: error Everything works if I use the commented out line with base64 encoded images which is very very slow (line 8).

What is the proper solution to simply show these images?

Upvotes: 5

Views: 5379

Answers (1)

lasagne
lasagne

Reputation: 641

Turning off web security in my main process did the trick.

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

Upvotes: 3

Related Questions