Ways to get image: from base64 or ArrayBuffer using Vue
P粉953231781
P粉953231781 2023-11-06 15:34:13
0
1
716

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粉953231781
P粉953231781

reply all(1)
P粉198814372

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template