2016-08-02 60 views
0

我有以下角JS指令「上傳的本地圖片:圖片上傳,採集圖像尺寸指令

app.directive('ngFileModel', ['$parse', function ($parse) { 
    return { 
     restrict: 'A', 
     link: function (scope, element, attrs) { 
      var model = $parse(attrs.ngFileModel); 
      var isMultiple = attrs.multiple; 
      var modelSetter = model.assign; 
      element.bind('change', function() { 
       var values = []; 
       angular.forEach(element[0].files, function (item) { 
        var value = { 
         // File Name 
         name: item.name, 
         //File Size 
         size: item.size, 
         //File URL to view 
         url: (URL || webkitURL).createObjectURL(item), 
         // File Input Value 
         _file: item 
        }; 
        values.push(value); 


       }); 
       scope.$apply(function() { 
        if (isMultiple) { 
         modelSetter(scope, values); 
        } else { 
         modelSetter(scope, values[0]); 
        } 
       }); 
      }); 
     } 
    }; 
}]); 

我現在想要獲取的圖像尺寸,但我不知道怎麼辦。 我試過類似的東西(行values.push以下(值)):

var img = new Image(); 
img.src = value.url; 

alert("Width: " + img.width); 

,但沒有奏效。我也嘗試過img.onload,但是我也沒有得到結果。

如何獲取圖像尺寸?

謝謝!

回答

0

由我自己解決了這個問題,image.onload是正確的方式去:

app.directive('ngFileModel', ['$parse', function ($parse) { 
    return { 
     restrict: 'A', 
     link: function (scope, element, attrs) { 
      var model = $parse(attrs.ngFileModel); 
      var isMultiple = attrs.multiple; 
      var modelSetter = model.assign; 
      element.bind('change', function() { 
       var values = []; 
       angular.forEach(element[0].files, function (item) { 

        var img = new Image(); 
        var imgheight = 0; 
        var imgwidth = 0; 
        var imgurl = (URL || webkitURL).createObjectURL(item); 

        img.src = imgurl; 
        img.onload = function() { 

         imgheight = img.height; 
         imgwidth = img.width; 
         //alert("Width: " + imgheight + " height: " + imgwidth); 

         var value = { 
         // File Name 
         name: item.name, 
         //File Size 
         size: item.size, 
         //File URL to view 
         url: imgurl, 
         // File Input Value 
         _file: item, 

         width: imgwidth, 

         height: imgheight, 

         mystyle: {} 
         }; 
         scope.$apply(function() { 
          values.push(value); 
         });      
        }; 
       }); 
       scope.$apply(function() { 
        if (isMultiple) { 
         modelSetter(scope, values); 
        } else { 
         modelSetter(scope, values[0]); 
        } 
       }); 
      }); 
     } 
    }; 
}]);