码蚁原创,请大神多多指教(嘻嘻,有同事帮忙改进的)
<script> /** * * @param id {string} input[file] elementID * @param width {number} 宽度 * @param quality{number} 压缩质量 {0.1-1} * @param callback{function} 回调函数 默认参数{code: number, data: string} */ function min_img(id,callback,width,quality){ var a={ width:width || 640, quality:quality || 0.8 } a.readFile= function(){ var file = this.files[0]; if (!/image\/\w+/.test(file.type)) { callback({code:101,data:'格式错误'}); }else{ var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { var img = new Image(), // quality = 0.8, //image quality canvas = document.createElement('canvas'), drawer = canvas.getContext("2d"); img.src=e.target.result; img.onload=function(){ a.height = a.width * (img.height / img.width); canvas.width=a.width; canvas.height=a.height; drawer.drawImage(img, 0, 0, a.width, a.height); a.result = canvas.toDataURL("image/jpeg",a.quality); callback({code:100,data:a.result}) } } } } if (typeof(FileReader) === 'undefined') { callback({code:102,data:'浏览器不支持'}); } else { var input = document.getElementById(id); input.addEventListener('change', a.readFile, false); } } </script>
啦啦啦~~~自己用着挺好的,希望能帮助到你哦