change(file) { let that = this,base64 = null fr = new FileReader(); fr.onload = function(e) { base64 = fr.result; }; fr.readAsDataURL(file); }
base64转2进制
1 2 3 4 5 6 7 8 9 10 11
change(data, mime) { data = data.split(',')[1]; data = window.atob(data); let ia = newUint8Array(data.length); for (let i = 0; i < data.length; i++) { ia[i] = data.charCodeAt(i); }; returnnew Blob([ia], { type: mime }); };
2进制转base64
1 2 3 4 5 6 7
change(bytes){ let bString = ""; for(let i = 0, len = bytes.length; i < len; ++i){ bString += String.fromCharCode(bytes[i]); } return btoa(bString); }
canvas绘制和压缩图片
1 2 3 4 5 6 7 8 9 10 11 12
paint(base64, bili, callback) { let img = new Image(); img.src = base64; img.onload = function() { let canvas = document.createElement("canvas"); let w = this.width / bili; let h = this.height / bili; canvas.setAttribute("width", w); canvas.setAttribute("height", h); canvas.getContext("2d").drawImage(this, 0, 0, w, h); } }
canvas转base64
1 2 3
let canvas = document.getElementById("canvas"); let base64 = canvas.toDataURL("image/png"); //还可以传个参数做图片质量的设置,在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92