title: How to preview .ai , .pdf format images before upload and convert into base64 in angularjs?
body: <p>I use this directive on input type="file" filread="uploadme.src", Now the challenging part is to first convert .ai/.pdf file to .jpg/.png/.gif and resize them and save the base64 text in API. I need solution to convert them first them resize using base64 Uri function as shown in code below.   </p>
  
  <pre><code>app.directive("fileread", [function() {
      return {
          scope: {
              fileread: "=",
              fileName: '='
          },
          link: function(scope, element, attributes) {
              element.bind("change", function(changeEvent) {
                  var file, name, reader, size, type;
                  var reader = new FileReader();
                  reader.onload = function(loadEvent) {
                      scope.fileName = {};
                      scope.$apply(function() {
                          var img = new Image();
                          img.src = (loadEvent.target.result);
                          img.onload = function() {
                              var size = calculateAspectRatioFit(this.width, this.height, 100, 100);
                              scope.fileName.size = "_" + size.width + "X" + size.height;
                              //Get resized image
                              scope.fileread = imageToDataUri(this, size.width, size.height);
  
                          }
                          scope.fileName.src = (loadEvent.target.result);
                          if (angular.isString(name)) {
                              return scope.fileName.name = name;
                          }
                      });
                  }
  
                  file = changeEvent.target.files[0];
                  name = file.name;
                  type = file.type;
                  size = file.size;
                  reader.readAsDataURL(file);
  
              });
          }
      }
  }]);
  </code></pre>
  
      
  
  <pre><code>//Resize the image (in the example 640 x 480px)
  function imageToDataUri(img, width, height) {
  
      // create an off-screen canvas
      var canvas = document.createElement('canvas'),
          ctx = canvas.getContext('2d');
  
      // set its dimension to target size
      canvas.width = width;
      canvas.height = height;
  
      // draw source image into the off-screen canvas:
      ctx.drawImage(img, 0, 0, width, height);
  
      // encode image to data-uri with base64 version of compressed image
      return canvas.toDataURL();
  }
  
  function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
  
      var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
  
      return {
          width: srcWidth * ratio,
          height: srcHeight * ratio
      };
  }
  </code></pre>