Angularjs, ng-flow, javascript technologies

Get image dimensions with ng-flow

This note shows how to get the width and height of an image inside of an AngularJS controller with the help of ng-flow library. First of all, you can get image dimensions by using the Image element constructor and specifying the following onload callback function:

1
2
3
4
5
6
7
8
var image = new Image();
image.src = "Image url or base64 string";
var width;
var height;
image.onload = function() {
    width = this.width;
    height = this.height;
};

But, since the ng-flow returns a file object, you need to get the file source first, which, as it is shown in the code sample above, can be either the image URL or the Base64 encoded string. Let's get the Base64 string by using the approach from the Get a Base64 Encoded Image Using Ng-flow in AngularJS note:

1
2
3
4
5
6
7
8
9
10
11
12
13
$scope.image = {};
var fileReader = new FileReader();
var image = new Image();
fileReader.onload = function (event) {
    image.src = event.target.result;
    image.onload = function() {
        $scope.image.width = this.width;
        $scope.image.height = this.height;
        // update scope after image is updated
        $scope.$apply();
    };
};
fileReader.readAsDataURL(flowFile.file);

As the result, the $scope.image will contain width and height of the image loaded with ng-flow.

Here you can play around with the CodePen example.

Looking to hire a software engineer?
Don't hesitate to contact us.

Comments