来自 base64 或 ArrayBuffer 的 Vue 图片
Vue image from base64 or ArrayBuffer
我有一个 flask 后端,它向 vue 前端发送一个图像 :
with open('my_image_file.jpg', 'rb') as f:
image_data = f.read()
emit('IMAGE', {'image_data': image_data})
在vue前端,图片最终应该显示在网页上。我想最简单的方法是以某种方式将图像保存在静态文件夹中。我会在我的商店中进行这样的操作:
const actions = {
SOCKET_IMAGE (commit, image) {
console.log("image received")
/* What needs to be done to save image in 'static/' ?*/
commit.commit('image_saved')
}
}
我也愿意使用其他方法来保存图像并将其呈现在网页上。可以直接在vuex store中保存图片吗?
您可以将图像数据存储在 Vuex 中
商店:
const state = {
imgData: null
}
假设您从 API 获取 base64
,提交原始数据:
commit('SET_IMAGE_DATA', image);
或者,如果您得到 ArrayBuffer
,请先转换它:
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 找到 base64 方法 here
并在您的模板中使用它:
<template>
<div>
<img :src="'data:image/png;base64,' + $store.state.imgData" />
</div>
</template>
我有一个 flask 后端,它向 vue 前端发送一个图像
with open('my_image_file.jpg', 'rb') as f:
image_data = f.read()
emit('IMAGE', {'image_data': image_data})
在vue前端,图片最终应该显示在网页上。我想最简单的方法是以某种方式将图像保存在静态文件夹中。我会在我的商店中进行这样的操作:
const actions = {
SOCKET_IMAGE (commit, image) {
console.log("image received")
/* What needs to be done to save image in 'static/' ?*/
commit.commit('image_saved')
}
}
我也愿意使用其他方法来保存图像并将其呈现在网页上。可以直接在vuex store中保存图片吗?
您可以将图像数据存储在 Vuex 中
商店:
const state = {
imgData: null
}
假设您从 API 获取 base64
,提交原始数据:
commit('SET_IMAGE_DATA', image);
或者,如果您得到 ArrayBuffer
,请先转换它:
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 找到 base64 方法 here
并在您的模板中使用它:
<template>
<div>
<img :src="'data:image/png;base64,' + $store.state.imgData" />
</div>
</template>