如何计算一张图片是横向还是纵向?

13

我正在使用jQuery创建图像库。是否有可能使用jQuery计算图像是横向还是纵向?

感谢您的支持。


检查高度/宽度比?你尝试过什么? - JNF
2
if width>length then landscape else portrait - Mark
@Christian Mark 谢谢你,Christian Mark。 - geovani075
1
Christian在评论中给出了答案。 - Jai
没问题。我不是很擅长 jQuery,所以我为你提供伪代码。 - Mark
如果图像中设置了EXIF方向(旋转)标志,上述内容就是正确的。例如,如果一张图像是横向的,并且EXIF标志指示顺时针旋转90度,那么该图像实际上是纵向的。 - Nimesh Chanchani
4个回答

32

你可以简单地比较图像的宽度和高度。

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

6

对我来说有效的方法是使用自然高度/宽度来获取原始属性。

       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;

        }

运行得非常好!谢谢。 - Sean

3
以下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";
}

}

这假定图像已经在UI中加载。我们不应该在实际计算比率之前等待图像加载事件触发吗? - Sunny R Gupta
2
为什么要使用 "height = height + height // 2" 来得到最佳高度? - RichardB

0
如果您动态添加媒体或使用dataUrl,则在元素放置在DOM之前无法访问其大小。 图片
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)
  })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接