2015-11-10 90 views
0

這裏是我們在客戶端實現的1024或768固定大小的jpeg大小調整。工作場景是用戶選擇一張圖像(原始圖像)他/她想上傳(沒有顯示)。如果原始圖像的尺寸大於1024或768,則按比例調整圖像大小。下面的代碼計算應該的寬度和高度並執行調整大小。使用javascript將jpeg圖像調整爲固定大小

有2 alert()顯示調整大小之前和之後的圖像大小。我們發現文件大小沒有減少。代碼有什麼問題?

$(function(){ 
    $('#uploaded_file_file_for_upload').change(function(){ 
     var _URL = window.URL || window.webkitURL; 
     var img, img_width = 0, img_height = 0, max_width = 1024, max_height = 768; 
     var f = $(this)[0].files[0]; 
     alert(f.size); 
     if (f.type == 'image/jpeg' || f.type == 'image/jpg') { 
      img = new Image(); 
      img.onload = function() { 
       img_width = this.width; 
       img_height = this.height; 
      }; 
      img.src = _URL.createObjectURL(f); 
      if (img_width > max_width){ 
       img_height = Math.ceil(img_height * max_width/img_width); 
       img_width = max_width; 
      } else if (img_height > max_height) { 
       img_width = Math.ceil(img_width * max_height/img_height); 
       img_height = max_height; 
      }; 
      resize(img, img_width, img_height); 
      var f1 = $(this)[0].files[0]; 
      alert(f1.size); 
     }; 

     function resize(image, width, height) { 
      var mainCanvas = document.createElement("canvas"); 
      mainCanvas.width = width; 
      mainCanvas.height = height; 
      var ctx = mainCanvas.getContext("2d"); 
      ctx.drawImage(image, 0, 0, width, height); 
      $('#uploaded_file_file_for_upload').attr('src', mainCanvas.toDataURL("image/jpeg")); 
     }; 

     return false; 

    }); 
}); 
+0

調試後,我們已經驗證調整圖片大小的作品。這個問題可以縮小到將大小調整後的圖像附加到代碼行$('#uploaded_file_file_for_upload')。attr('src',mainCanvas.toDataURL(「image/jpeg」)); #uploaded_file_file_for_upload。 – user938363

回答

0

檢查naturalWidth從圖像而不是CSS width

+0

圖像寬度沒有問題。 – user938363

+0

請考慮編輯您的帖子,以添加更多關於您的代碼的解釋以及爲什麼它可以解決問題。一個主要包含代碼的答案(即使它正在工作)通常不會幫助OP瞭解他們的問題。如果這只是猜測,也建議您不要發佈答案。一個好的答案會有一個合理的理由解釋爲什麼它可以解決OP的問題。 – Drenmi