mike
mike

Reputation: 1663

How can I rotate a base64 image in AngularJS

I have a json source that contains base64 images, and I would like to display them all in portrait. I think I need to build an array of Image objects, and rotate them as I build the array, but I'm not sure how to display the image objects in the view.

This is the array I've built

angular.forEach($scope.trayDetails.tray_images, function(trayImage) {
    var myBase64 = "data:image/png;base64,"+trayImage.data;
    var img = new Image();
    img.src = myBase64;
    if (img.width>img.height ) {
        $(img).css({
            'transform': "rotate(90deg)"
        });
    }
    $scope.savedPictures.push(img);
});

But now I'm not sure what to do with the array, I tried these 2 methods with no luck

<li ng-repeat="savedPicture in savedPictures" class="photo">
    {{savedPicture}}
</li>

<li ng-repeat="savedPicture in savedPictures" class="photo">
    <img ng-src="{{savedPicture}}" />
</li>

Upvotes: 1

Views: 1079

Answers (1)

Huy Hoang Pham
Huy Hoang Pham

Reputation: 4147

The solution is easier than you think:

angular.forEach($scope.trayDetails.tray_images, function(trayImage) {
   var myBase64 = "data:image/png;base64,"+trayImage.data;
   var img = new Image();
   img.src = myBase64;
   img.isRotated = img.width > img.height; //Use css class to rotate
   $scope.savedPictures.push(img);
});

Then add the img into html,:

<li ng-repeat="savedPicture in savedPictures" class="photo">
     <img ng-class="{rotateImg: savedPicture.isRotated}" ng-src="{{savedPicture.src}}" />
</li>

The img tags will have rotateImg class if its width is greater than its height. The css for rotateImg class is:

.rotateImg : { transform: rotate(90deg); }

Upvotes: 1

Related Questions