图片类型
URL转base64
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function convertImgToBase64 (url, callback, outputFormat){ let canvas = document.createElement('CANVAS'), ctx = canvas.getContext('2d'), img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); let dataURL = canvas.toDataURL(outputFormat || 'image/png'); callback.call(this, dataURL); canvas = null; }; img.src = url; },
|
案例
1 2 3 4
| convertImgToBase64('https:///xxxx.png', function (base64Img) { console.log(base64Img) })
|
base64转file
1 2 3 4 5 6 7 8 9 10 11 12
| function dataURLtoFile (dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } console.log(new File([u8arr], filename, { type: mime })) return new File([u8arr], filename, { type: mime }); }
|