Home  >  Q&A  >  body text

Ways to get image: from base64 or ArrayBuffer using Vue

I have a Flask backend that 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})

In the Vue front-end, this image should eventually be displayed on the web page. I guess the easiest way is to save the images in a static folder. In my store, I would have an action like this:

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

    /* 需要做什么来将图片保存在 'static/' 中?*/

    commit.commit('image_saved')
  }
}

I would also be happy to try other methods of saving images and rendering them on the web. Can I save images directly in the Vuex store?

P粉953231781P粉953231781253 days ago434

reply all(1)I'll reply

  • P粉198814372

    P粉1988143722023-11-07 13:53:09

    You can store image data in Vuex

    storage:

    const state = {
      imgData: null
    }
    

    Assuming you get base64 from the API, please submit the original data:

    commit('SET_IMAGE_DATA', image);
    

    Or, if you get ArrayBuffer, please convert 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);
    

    Find the method of converting ArrayBuffer to base64 herehere

    and use it in your template:

    <template>
      <div>
        <img :src="'data:image/png;base64,' + $store.state.imgData" />
      </div>
    </template>
    

    reply
    0
  • Cancelreply