前端-如何将canvas画布转换为二进制文件
一、背景
canvas是HTML5中重要的元素,它提供了强大的图形的处理功能,例如:像素处理、绘制等等。在使用摄像头拍摄人脸后,需要提交后端进行人脸识别,后端要求前端调用接口时上传二进制文件。
二、实现方法
1、将base64转换为blob
dataURLtoBlob: function(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });//返回blob对象
}
2、将blob转换为file
blobToFile: function(theBlob, fileName){
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
3、调用接口传参
let blob = self.dataURLtoBlob(imgBase);
let file = self.blobToFile(blob, '');
let fd = new FormData()
fd.append('file', file)
这篇博客介绍了如何在前端将canvas画布转换为二进制文件,以满足后端接口要求。首先,通过dataURLtoBlob函数将canvas的base64编码转换为blob对象,然后使用blobToFile方法将其转化为file,最后通过FormData将file对象添加到请求参数中,以便上传到后端进行人脸识别。

被折叠的 条评论
为什么被折叠?



