我有一个Flask后端,根据这里的描述,将一张图片发送给Vue前端:
with open('my_image_file.jpg', 'rb') as f:
image_data = f.read()
emit('IMAGE', {'image_data': image_data})
在Vue前端,最终应该在网页上显示这张图片。我猜最简单的方法是将图片保存在静态文件夹中。在我的store中,我会有一个像这样的action:
const actions = {
SOCKET_IMAGE (commit, image) {
console.log("image received")
/* 需要做什么来将图片保存在 'static/' 中?*/
commit.commit('image_saved')
}
}
我也乐意尝试其他保存图片并在网页上渲染的方法。我能直接将图片保存在Vuex store中吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以将图像数据存储在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>