<!DOCTYPE html> <html> <head> <meta charset="{CHARSET}"> <title>圖片本地壓縮</title> </head> <body> <input type="file" id="file"/> <img src="" id="img"/> <script> var oInput = document.getElementById ( 'file' ) var oImg = document.getElementById("img"); oInput.onchange = function(){ var fileData = oInput.files[ 0 ]; base64(fileData,function(base64Data){ //base64Data:處理成功返回的圖片base64 oImg.setAttribute("src",base64Data); }); } function base64(file,backData){ /* * file:input上傳圖片 * backData:處理完成回調函數 * */ var reader = new FileReader(); var image = new Image(); var canvas = createCanvas(); var ctx = canvas.getContext("2d"); reader.onload = function(){ // 文件加載完處理 var result = this.result; image.onload = function(){ // 圖片加載完處理 var imgScale = imgScaleW(1000,this.width,this.height); canvas.width = imgScale.width; canvas.height = imgScale.height; ctx.drawImage(image,0,0,imgScale.width,imgScale.height); var dataURL = canvas.toDataURL('image/jpeg'); // 圖片base64 ctx.clearRect(0,0,imgScale.width,imgScale.height); // 清除畫布 backData (dataURL); //dataURL:處理成功返回的圖片base64 } image.src = result; }; reader.readAsDataURL(file); } function createCanvas(){ // 創建畫布 var canvas = document.getElementById('canvas'); if(!canvas){ var canvasTag = document.createElement('canvas'); canvasTag.setAttribute('id','canvas'); canvasTag.setAttribute('style','display:none;');//隱藏畫布 document.body.appendChild(canvasTag); canvas = document.getElementById('canvas'); } return canvas; } function imgScaleW(maxWidth,width,height){ /* maxWidth:寬度或者高度最大值 * width:寬度 * height:高度 * */ var imgScale = {}; var w = 0; var h = 0; if(width <= maxWidth && height <= maxWidth){ // 如果圖片寬高都小於限制的最大值,不用縮放 imgScale = { width:width, height:height } }else{ if(width >= height){ // 如果圖片寬大於高 w = maxWidth; h = Math.ceil(maxWidth * height / width); }else{ // 如果圖片高大於寬 h = maxWidth; w = Math.ceil(maxWidth * width / height); } imgScale = { width:w, height:h } } return imgScale; } </script> </body> </html>
