title: Implementation of resize jpeg image with javascript to a fixed size
body: <p>Here is our implementation of a jpeg resize on client side to a fixed size of 1024 or 768. The work scenario is that a user selects an image (original image) he/she wants to upload (without display). If dimension of the original image is larger than 1024 or 768, then resize the image proportionally. The code below calculates the width and height of should-be and performs resize.</p>
  
  <p>There are 2 <code>alert()</code> to show the image size before and after resize. We find that the file size is not reduced. What could be wrong with the code?</p>
  
  <pre><code>$(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 &gt; max_width){
                  img_height = Math.ceil(img_height * max_width / img_width);
                  img_width = max_width;
              } else if (img_height &gt; 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;
  
      });
  });
  </code></pre>