Krichevskoy
Krichevskoy

Reputation: 254

How to Rotate image before displaying in web using JavaScript?

I just want to know, can I detect attributes of an image before displaying it on the web? In my case, I have a thousand photos. I want to display them on my web page but some photos have a different orientation (like Landscape and Portrait).

Can I detect the width and height of the image before it is displayed on my web page?

Maybe using JavaScript like:

If height>width than rotate
else just display.

Is there any JavaScript function for doing that? Just for getting the attribute not displaying it. Is there a trick?

Upvotes: 1

Views: 1246

Answers (2)

Donovan Charpin
Donovan Charpin

Reputation: 3397

When your page is loading, you can control each <img/>

//function rotation
jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
};

// When your page is loading
$( window ).load(function() {
    // Each image, you can change selector
    $('img').each(function(){
        if(this.height() < this.width()){ // Size control
            $(this).rotate(90); // rotation function call with the angle in degrees
        }
    });
});

Upvotes: 1

Mr. Smith
Mr. Smith

Reputation: 639

You have to wait until it is loaded.

setInterval(function () {
   if(loaded)
   {
      clearInterval(wait);
   }
   else
   {
      log(img.width, 'x', img.height);
   }
}, 0);

I found an Example here.

Hope it helps.

Upvotes: 1

Related Questions