/**
* 1.0 FileReader
*/
// let img = document.querySelector("input");
// img.onchange = function(e){
// let file = this.files[0];
// imgToBase64(file,show);
// }
function imgToBase64(file,callback){
let f = new FileReader();
f.readAsDataURL(file);
f.onload = function(){
let base64 = f.result;
callback.call(this,base64)
}
}
function show(code) {
console.log('size:'+code);
document.querySelector('img').setAttribute('src',code);
}
/**
* 2.0 canvas重绘
* 可以压缩图片
*/
function imgToBase64(url,callback){
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.crossOrigin = 'Anonymous';
img.src = url;
img.onload = function () {
console.log(url)
canvas.height = this.height; //指定画板的高度,自定义
canvas.width = this.width; //指定画板的宽度,自定义
ctx.drawImage(img, 0, 0,this.width,this.height); //参数可自定义
var dataURL = canvas.toDataURL("image/jpeg",1);
callback.call(this, dataURL); //回掉函数获取Base64编码
canvas = null;
};
}
/**
* Base64.js
*/
let code = $.base64.encode('223841');
console.log('base64编码后:'+code);
console.log('base64解码后:'+$.base64.decode(code));
//imgToBase64('https://pics0.baidu.com/feed/3b292df5e0fe992518448ccedf8964d58cb17194.jpeg?token=a8af55e099d7507f313330013f84d5dc',show)
08-26
4434
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-23
7623
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交