js-图片转换

base64转图片file:
base64ToFile(base64data, filename = "file") {
  // base64转图片对象
  let arr = base64data.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let suffix = mime.split("/")[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  });
}
图片file转URL:
fileToUrl(file) {
  // 图片data转换URL
  let url = null;
  if (window.createObjectURL !== undefined) {
  // basic
    url = window.createObjectURL(file);
  } else if (window.URL !== undefined) {
    // mozilla(firefox)
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL !== undefined) {
    // webkit or chrome
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}
canvas转base64:
canvasToBase64(canvasId) {
  var canvas = document.getElementById(canvasId);
  let imgBase64 = canvas.toDataURL("image/png");
}
base64保存为本地图片:
base64SaveAsFile(data,fileType){
  //1.图片的类型  获取到的图片格式 data:image/Png;base64,......
  let type
  if(fileType){
    type = fileType
  }else{
    type= 'png'
  }
  //2 将mime-type改为image/octet-stream,强制让浏览器下载
  var fixtype=function(type){
    type=type.toLocaleLowerCase().replace(/jpg/i,'jpeg');
    let r=type.match(/png|jpeg|bmp|gif/)[0];
    return 'image/'+r;
  };
  let imgdata=data.replace(fixtype(type),'image/octet-stream');
  //3 图片的名字
  let filename='img'+new Date().getTime()+'.'+type;
  //4 将图片保存到本地
  var savaFile=function(data,filename){
    let save_link=document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href=data;
    save_link.download=filename;
    let event=document.createEvent('MouseEvents');
    event.initMouseEvent('click',true,false,window,0,0,0,0,0,false,false,false,false,0,null);
    save_link.dispatchEvent(event);
  };
  savaFile(imgdata,filename);
}

你可能感兴趣的:(js-图片转换)