图片转base64并压缩大小

<input id="file" type="file"  capture="microphone" accept="image/*"> 
 1 $("#file").change(function(){
 2 var m_this = this;
 3       cutImageBase64(m_this,null,400,0.8);  
 4 })
 5 function cutImageBase64(m_this,id,wid,quality) {
 6  
 7     var file = m_this.files[0];
 8     var URL = window.URL || window.webkitURL;
 9     var blob = URL.createObjectURL(file);
10     var base64;
11 var img = new Image();
12     img.src = blob;
13     img.onload = function() {
14         var that = this;
15         //生成比例
16         var w = that.width,
17             h = that.height,
18             scale = w / h;
19             w = wid || w;
20             h = w / scale;
21 //生成canvas
22         var canvas = document.createElement('canvas');
23         var ctx = canvas.getContext('2d');
24         $(canvas).attr({
25             width: w,
26             height: h
27         });
28         ctx.drawImage(that, 0, 0, w, h);
29         // 生成base64            
30         base64 = canvas.toDataURL('image/jpeg', quality || 0.8);
31 console.log(base64)
32     };
33 }

猜你喜欢

转载自www.cnblogs.com/chenpeikun/p/12149269.html