JS图片转换格式 (转Blob)

base64转Blob

//ndata为base64格式地址
let arr = ndata.split(','), mime = arr[0].match(/:(.*?);/)[1],
  bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
}
let bdata = new Blob([u8arr], {type: mime})

通过XHR的方法来转转Blob

let xhr = new XMLHttpRequest();
xhr.open("get", "http://mybg.oss-cn-hangzhou.aliyuncs.com/2019031510452423", true);
xhr.responseType = "blob";
xhr.onload = function (res) {
  if (this.status == 200) {
    var blob = this.response;
    var img = document.createElement("img");
    img.onload = function (e) {
      window.URL.revokeObjectURL(img.src); // 清除释放
    };
    //img.src为Blob格式的img资源
    img.src = window.URL.createObjectURL(blob);
    console.log(img.src)
  }
}
xhr.send();

猜你喜欢

转载自blog.csdn.net/xr510002594/article/details/89306736