我正在尝试使用cordova-plugin-camera拍照.我希望结果是File或Blob对象.
但是,destinationType
必须是DATA_URL或FILE_URI之一.
文档说明:
DATAURL can be very memory intensive and cause app crashes or out of memory errors. Use FILEURI or NATIVE_URI if possible
但是,据我所知,将这样的文件uri转换为Blob需要执行以下步骤:
>在< img /上渲染uri
>在画布上绘制图像
>将canvas作为base64读取
>将base64转换为Blob
我发现很难相信这比使用DATAURL更有效.所以我也可以使用DATAURL来跳过步骤1-3.
有没有办法让照片以更有效的方式拍摄为Blob对象?
解决方法
不幸的是,您无法从Cordova相机插件中提取BLOB.
获取BLOB的方法是将base64编码的字符串转换为BLOB并使用它.
这是一种方法(符合ES6),允许您转换为BLOB,只有sliceSize可以提高内存效率.
/** * Turn base 64 image into a blob,so we can send it using multipart/form-data posts * @param b64Data * @param contentType * @param sliceSize * @return {Blob} */ private getBlob(b64Data:string,contentType:string,sliceSize:number= 512) { contentType = contentType || ''; sliceSize = sliceSize || 512; let byteCharacters = atob(b64Data); let byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { let slice = byteCharacters.slice(offset,offset + sliceSize); let byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } let byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } let blob = new Blob(byteArrays,{type: contentType}); return blob; }