2015-11-10 82 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