简体   繁体   English

如何计算图像是横向还是纵向

[英]how to Calculate whether an image is landscape or portrait

I am creating an image gallery with jquery.我正在用 jquery 创建一个图片库。 Is there any possibilities to Calculate whether an image is landscape or portrait using jquery?是否有可能使用 jquery 计算图像是横向还是纵向?

Thanks for your support.谢谢您的支持。

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.
}

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;

        }

Below javascript function will return the best suited Orientation下面的 javascript 函数将返回最适合的方向

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";
}

}

If you add the media dynamically or if you use dataUrl , you can't access the size before the element is placed in DOM.如果动态添加媒体或使用dataUrl ,则无法在将元素放入 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) })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM