常见图片格式转换
常见格式介绍
file对象 转换为 base64
let reader =newFileReader();
reader.readAsDataURL(file[0])
console.log(reader)
base64 转换为 Blob
base64ToBlob(urlData){let arr = urlData.split(",");let mime = arr[0].match(/:(.*?);/)[1];let bstr =atob(arr[1]);let n = bstr.length;let u8arr =newUint8Array(n);while(n--){
u8arr[n]= bstr.charCodeAt(n);}returnnewBlob([u8arr],{type: mime });}
base64 转换为 file
base64toFile(dataurl, fileName){let arr = dataurl.split(",");// let mime = arr[0].match(/:(.*?);/)[1];let bstr =atob(arr[1]);let n = bstr.length;let u8arr =newUint8Array(n);while(n--){
u8arr[n]= bstr.charCodeAt(n);}returnnewFile([u8arr], fileName);}
Blob 转换为 blob地址
BlobToBlobURL(BlobFile,type){let blob =newBlob([BlobFile],{type: type });// 图片:"image/jpeg"const blobUrl =URL.createObjectURL(blob);return blobUrl ;}
blob 转换为 ArrayBuffer
blobToArrayBuffer(){let blob =newBlob([1,2,3,4])let reader =newFileReader();
reader.onload=function(result){
console.log(result);}
reader.readAsArrayBuffer(blob);}
buffer转换为 Blob
let blob =newBlob([buffer])
图片URL 转换为 blob和base64
urlToBlobBase64(imgUrl){returnnewPromise((resolve)=>{
window.URL= window.URL|| window.webkitURL;var xhr =newXMLHttpRequest();
xhr.open("get", imgUrl,true);
xhr.responseType ="blob";
xhr.onload=function(){if(this.status ==200){var blob =this.response;let oFileReader =newFileReader();
oFileReader.onloadend=function(e){resolve({ blob,base64: e.target.result });};
oFileReader.readAsDataURL(blob);}else{reject(newError("异常"));}};
xhr.send();
xhr.onerror=()=>{reject(newError("异常"));};});}
Blob 转 base64
functionblobToDataURI(blob,callback){var reader =newFileReader();
reader.readAsDataURL(blob);
reader.onload=function(e){callback(e.target.result);};}
// 调用blobToDataURI(blobData,function(result){
console.log(result);});
本文转载自: https://blog.csdn.net/qq_37831545/article/details/127440816
版权归原作者 一朵野花压海棠 所有, 如有侵权,请联系我们删除。
版权归原作者 一朵野花压海棠 所有, 如有侵权,请联系我们删除。