1.url 转图片流
// url 转 图片流 const urlToFile = (url, imageName) => { return new Promise((resolve, reject) => { let blob = null; const xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.setRequestHeader('Accept', 'image/png'); xhr.responseType = "blob"; xhr.onload = () => { blob = xhr.response; let imgFile = new File([blob], imageName, { type: 'image/png' }); resolve(imgFile); }; xhr.onerror = (e) => { reject(e); }; xhr.send(); }); }; (async () => { const baseurl = 'https://img1.baidu.com/it/u=3622442929,3246643478&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'; const file = await urlToFile(baseurl); console.log('file', file); })()
2. url转base64
// url 转 base64 const urlToBase64 = (url) => { return new Promise((resolve, reject) => { const image = new Image(); image.setAttribute('crossOrigin', 'anonymous'); image.src = url; image.onload = function(){ const canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0, image.width, image.height); const ext = image.src.substring(image.src.lastIndexOf(".")+1).toLowerCase(); const base64 = canvas.toDataURL("image/"+ext); resolve(base64); } image.onerror = (e) => { reject(e); }; }); } (async () => { const baseurl = 'https://img1.baidu.com/it/u=3622442929,3246643478&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'; const base64 = await urlToBase64(baseurl); console.log('base64', base64); })()
3.base64 转图片流
// base64 转 图片流 const base64ToFile = (base64, filename = 'file') => { const arr = base64.split(','); const mime = arr[0].match(/:(.*?);/)[1]; const suffix = mime.split('/')[1]; const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); }; const file = new File([u8arr], `${filename}.${suffix}`, { type: mime }); return file; } (async () => { const baseurl = 'https://img1.baidu.com/it/u=3622442929,3246643478&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'; const base64 = await urlToBase64(baseurl); console.log('base64', base64); const file = await base64ToFile(base64); console.log('file', file); })()
4.base64转url
// base64 转 图片url const base64ToUrl = (base64, filename = 'file') => { const arr = base64.split(','); const mime = arr[0].match(/:(.*?);/)[1]; const suffix = mime.split('/')[1]; const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); }; const file = new File([u8arr], `${filename}.${suffix}`, { type: mime }); return URL.createObjectURL(file); } (async () => { const baseurl = 'https://img1.baidu.com/it/u=3622442929,3246643478&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'; const base64 = await urlToBase64(baseurl); console.log('base64', base64); const url = await base64ToUrl(base64); console.log('url', url); })()
标签:const,url,image,base64,file,new,图片 From: https://www.cnblogs.com/webtown/p/16831400.html