geovani075
geovani075

Reputation: 377

how to Calculate whether an image is landscape or portrait

I am creating an image gallery with jquery. Is there any possibilities to Calculate whether an image is landscape or portrait using jquery?

Thanks for your support.

Upvotes: 14

Views: 32164

Answers (4)

Qwerty
Qwerty

Reputation: 31949

If you add the media dynamically or if you use dataUrl, you can't access the size before the element is placed in DOM.

image
resolveImage(fileEntry) // implementation detail
  .then(src => {
    const img = document.importNode(itmp, true) // use a template or `createElement()`
    img.src = src // 'data:image/svg+xml;base64,PHN2Z...'
    img.onload = ({target: el}) => (el.height > el.width) ? el.classList.add('portrait') : el.classList.add('landscape')
    grid.appendChild(img)
  })
video
resolveVideo(fileEntry)
  .then(({src, type}) => {
    const vid = document.importNode(vtmp, true)
    vid.type = type
    vid.src = src
    vid.onloadeddata = ({target: el}) => (el.videoHeight > el.videoWidth) ? el.classList.add('portrait') : el.classList.add('landscape')
    grid.appendChild(vid)
  })

Upvotes: 0

Darren Street
Darren Street

Reputation: 1830

This worked for me, using the natural height/width to get the original properties.

       function imageOrientation(src) {

            var orientation,
            img = new Image();
            img.src = src;

            if (img.naturalWidth > img.naturalHeight) {
                orientation = 'landscape';
            } else if (img.naturalWidth < img.naturalHeight) {
                orientation = 'portrait';
            } else {
                orientation = 'even';
            }

            return orientation;

        }

Upvotes: 7

Navneet Singh
Navneet Singh

Reputation: 1198

Below javascript function will return the best suited Orientation

function get_orientation(src){

img = new Image();
img.src = src;
var width = img.width;
var height = img.height;
height = height + height // Double the height to get best
//height = height + (height / 2) // Increase height by 50%

if(width > height) { 
return "landscape"; 
} else {
return "portrait";
}

}

Upvotes: 3

Martyn
Martyn

Reputation: 384

You can simply compare width and height of the image.

var someImg = $("#someId");
if (someImg.width() > someImg.height()){
    //it's a landscape
} else if (someImg.width() < someImg.height()){
    //it's a portrait
} else {
    //image width and height are equal, therefore it is square.
}

Upvotes: 33

Related Questions