1. 程式人生 > >javaScript:壓縮圖片並上傳

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 ){ var objThis = this; // 壓縮圖片需要的一些元素和物件 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 ) } } }; }, file.type || 'image/png', ); }, explain:function(){ console.log( 'new uploadThumbnail({' ); console.log( ' name:imgFileName || "imgs",' ); console.log( ' formName:formName || "forms",' ); console.log( ' max:[maxWidth,maxHeight] || [ 400*400 ],' ); console.log( ' file:inputFile,' ); console.log( ' url:URL,' ); console.log( ' dataType:"json" || "text"' ); console.log( ' success:functon(data){} Callback function on success' ); console.log( '});' ); console.log( "obj.newImgObj:Compressed image object" ) } } win.uploadThumbnail = uploadThumbnail; }(window))