<input type="file" id="textfile" accept="image/*"/>上传
<div class="upP_img1"></div>预览框
$('#textfile').on('change', function() {
var reader = new FileReader();//新建获取file的读取文件var imgsrc = null;
var _file = this.files[0], //获取的的图片
fileType = _file.type; //图片类型
console.log(fileType);
reader.readAsDataURL(this.files[0]);//输出base64图片
reader.onload = function(e) {//字面理解是加载图片,得到结果吧,不是很理解
imgsrc = this.result;//输出结果
// 压缩
var image=new Image();//新建图片
image.src=imgsrc;
image.onload=function(){
var cvs=document.createElement('canvas');//画布
var cvx =cvs.getContext('2d');//
// draw image params
cvs.width=this.width;
cvs.height=this.height;
cvx.drawImage(this, 0, 0,this.width,this.height);//画图
var newImageData = cvs.toDataURL(fileType,0.2);//这是压缩,具体的看.toDataURL api 输出base64
console.log(newImageData);
$('.upP_img1').html('<img id="newimg" src="' + newImageData + '">');console.log(this.width+'--'+this.height);
// 上传图片后的以宽高充满判断
var imgscale2 = this.width / this.height;
var photoscale2 = $('.upP_img1').width() /$('.upP_img1').height();
if (imgscale2 > photoscale2) {
$('#newimg').css({ "width": "100%", "height": "auto" });
} else {
$('#newimg').css({ "width": "auto", "height": "100%" });
}
}
}
});
$.ajax({
url:url,
type:post,
data:JSON.stringify($('#newimg').attr('src')),success:function(){},error:function(){}
});
值得一提的是,canvs画出来的图片比上传的原图片要大,39k的原图画出来有180k 这是最骚的,5m压缩20%出来有500k。
http://www.zhangxinxu.com/study/201707/js-compress-image-before-upload.html这是别人的专业答案