1

I have a flask backend, which sends an image to the vue frontend as described here:

with open('my_image_file.jpg', 'rb') as f:
    image_data = f.read()
emit('IMAGE', {'image_data': image_data})

On the vue frontend, the image should ultimately be shown on the webpage. I guess the easiest way would be to somehow save the image in the static Folder. I would have an action like this in my store:

const actions = {
  SOCKET_IMAGE (commit, image) {
    console.log("image received")

    /* What needs to be done to save image in 'static/' ?*/

    commit.commit('image_saved')
  }
}

I am also open for alternative ways to save the image and render it on the webpage. Can I save the image directly in the vuex store?

Dan
  • 59,490
  • 13
  • 101
  • 110
chefhose
  • 2,399
  • 1
  • 21
  • 32

1 Answers1

3

You can store the image data in Vuex

Store:

const state = {
  imgData: null
}

Assuming you're getting base64 from the API, commit the raw data:

commit('SET_IMAGE_DATA', image);

Or, if you're getting an ArrayBuffer, convert it first:

function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

const imgData = _arrayBufferToBase64(image)
commit('SET_IMAGE_DATA', imgData);

ArrayBuffer to base64 method found here

And use it in your template :

<template>
  <div>
    <img :src="'data:image/png;base64,' + $store.state.imgData" />
  </div>
</template>
Dan
  • 59,490
  • 13
  • 101
  • 110
  • `````` appears in the html, but image could not be loaded (broken image symbol) any ideas? – chefhose Nov 27 '20 at 21:25
  • Seems you're getting an ArrayBuffer. Try my updated answer – Dan Nov 27 '20 at 21:34
  • @Dan `$store.state.imgData` -> why not teach to create a getter instead? – balexandre Nov 27 '20 at 21:58
  • @balexandre It's not a great use case for a getter; a custom component would be more appropriate. Plus I don't wish to confuse with tangential topics, especially since this one is already tackling image conversion – Dan Nov 28 '20 at 13:54