前端-如何将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)