javaScript:压缩图片并上传
html代码:
<input id="file" type="file" name="filesName">
js代码:
var fileElement = document.getElementById('file'); fileElement.onchange = function(){ var file = event.target.files[0]; var upload = new uploadThumbnail({ // name:"imgFileName", //缺省为 'imgs' // formName:"formName", //缺省为 'forms' // max:[maxWidth,maxHeight], //缺省为 [400*400] file:file, url:"./thumbnail.php", dataType:"json", //缺省为 'text' success:function( data ){ console.info( data ); //打印接收的数据 //this.newImgObj 为压缩后的图片对象 document.body.append( this.newImgObj ) // 将图片加入页面 } }); upload.explain(); //在控制台打印说明 }
uploadThumbnail 对象:
(function(win,undefined){ 'use strict' var uploadThumbnail = function( obj ){ this.newImgObj = null; this.init( obj ); this.success = obj.success || function () {}; } uploadThumbnail.prototype = { constructor:uploadThumbnail, // 入口函数 init:function( obj ){ this.compressPictures( obj ); }, // 压缩图片 并将画布传入上传函数 compressPictures:function( obj ){ obj = obj || {}; obj.file = obj.file || "undefined"; obj.url = obj.url || "undefined"; var objThis = this; if( obj.file == "undefined" || obj.url == "undefined" ){ console.info( "uploadThumbnail: 'file' and 'url' are required" ); return false }; // 压缩图片需要的一些元素和对象 var reader = new FileReader(), newImg = new Image(); // 缩放图片需要的canvas var canvas = document.createElement( 'canvas' ); var context = canvas.getContext( '2d' ); if ( obj.file.type.indexOf( "image" )==0 ) { reader.readAsDataURL( obj.file ); // 文件base64化,以便获知图片原始尺寸 reader.onload = function( e ) { newImg.src = e.target.result; // base64地址图片加载完毕后 newImg.onload = function () { // 图片原始尺寸 var originWidth = this.width; var originHeight = this.height; // 最大尺寸限制 var maxWidth, maxHeight; try{ maxWidth = obj.max[0]; maxHeight = obj.max[1]; }catch( err ){ maxWidth = 400; maxHeight = 400; } // 目标尺寸 var targetWidth = originWidth, targetHeight = originHeight; // 图片尺寸超过400x400的限制 if ( originWidth > maxWidth || originHeight > maxHeight ) { if ( originWidth / originHeight > maxWidth / maxHeight ) { // 更宽,按照宽度限定尺寸 targetWidth = maxWidth; targetHeight = Math.round( maxWidth * ( originHeight / originWidth ) ); } else { targetHeight = maxHeight; targetWidth = Math.round( maxHeight * ( originWidth / originHeight ) ); } } // canvas对图片进行缩放 canvas.width = targetWidth; canvas.height = targetHeight; // 清除画布 context.clearRect( 0,0,targetWidth,targetHeight ); // 图片压缩 context.drawImage( newImg,0,0,targetWidth,targetHeight); // 完成画布传入上传 objThis.upFile( obj,canvas ); }; }; }else{ return false; } }, upFile:function( obj,canvas ){ var objThis = this; // canvas转为blob并上传 canvas.toBlob( function (blob) { // 生成图片 var newImg = document.createElement("img"), url = URL.createObjectURL(blob); newImg.onload = function() { URL.revokeObjectURL(url); }; obj.img == true ? newImg.src = canvas.toDataURL() : newImg.src = url; objThis.newImgObj = newImg; // 创建表单数据 var formData = new FormData(); formData.append( obj.formName || 'forms',blob,obj.name || 'imgs' ); // 图片上传 var request = new XMLHttpRequest(); // obj.async ? obj.async = true : obj.async = false; request.open( "POST",obj.url,true ); request.send( formData ); request.onreadystatechange = function() { if ( request.readyState == 4 && request.status == 200 ) { if( obj.dataType=="JSON" || obj.dataType=="json" ){ try{ objThis.success( JSON.parse(request.responseText) ) }catch( err ){ console.info( "banfeng reminds you: Error in converting received data to 'JSON' format" ) } }else{ objThis.success( request.responseText ) } } }; }, obj.file.type || 'image/png', ); }, explain:function(){ console.group( "This is uploadThumbnail" ); console.log( 'new uploadThumbnail({' + '\n\tname:imgFileName || "imgs",' + '\n\tformName:formName || "forms",' + '\n\tmax:[maxWidth,maxHeight] || [ 400*400 ],' + '\n\tfile:inputFile,' + '\n\turl:URL,' + '\n\tdataType:"json" || "text"' + '\n\tsuccess:functon(data){} Callback function on success' + '\n});' + "\nobj.newImgObj:Compressed image object" ) console.groupEnd(); } } win.uploadThumbnail = uploadThumbnail; }(window));