前端Vue+后端Flask:从后端获取图片并在前端展示
后端代码:# 项目的根目录 起服务后,相对路径可能会改变basedir = os.path.abspath(os.path.dirname(__file__))@app.route('/getPic',methods=['GET', 'POST'])def findpic():img_url = basedir+'/static/tt.png'print(img_url)with open(img
·
后端代码:
# 项目的根目录 起服务后,相对路径可能会改变
basedir = os.path.abspath(os.path.dirname(__file__))
@app.route('/getPic',methods=['GET', 'POST'])
def findpic():
img_url = basedir+'/static/tt.png'
print(img_url)
with open(img_url, 'rb') as f:
a = f.read()
'''对读取的图片进行处理'''
img_stream = io.BytesIO(a)
img = Image.open(img_stream)
imgByteArr = io.BytesIO()
img.save(imgByteArr,format='PNG')
imgByteArr = imgByteArr.getvalue()
print(imgByteArr)
return imgByteArr
前端代码:
- template:
<button @click="getPic">获取图片</button>
<img :src="picurl" alt="beachball" />
- script的methods中:
//从服务器获取图片
getPic() {
var that = this;
axios({
method: "get",
url: "http://127.0.0.1:5000/getPic",
responseType: "arraybuffer", // 最为关键
}).then(function (response) {
that.picurl =
"data:image/jpeg;base64," + that.arrayBufferToBase64(response.data);
});
},
// ArrayBuffer转为base64字符串
arrayBufferToBase64(buffer) {
//第一步,将ArrayBuffer转为二进制字符串
var binary = "";
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
//将二进制字符串转为base64字符串
return window.btoa(binary);
},
- script的data中:
picurl: "",//图片url
效果:
点击前:
点击后:
更多推荐
已为社区贡献4条内容
所有评论(0)