【问题标题】:how to Calculate whether an image is landscape or portrait如何计算图像是横向还是纵向
【发布时间】:2013-05-29 07:01:30
【问题描述】:

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

感谢您的支持。

【问题讨论】:

  • 检查高宽比?你试过什么?
  • if width>length then landscape else portrait
  • @Christian Mark 感谢Christian Mark
  • christian 作为评论给出了答案。
  • 没有问题。我不太擅长 jQuery,所以我提供了伪代码。

标签: jquery image-gallery


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这对我有用,使用自然高度/宽度来获取原始属性。

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

    【讨论】:

    • 工作就像一个魅力!谢谢
    【解决方案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 中。在实际计算比率之前,我们是否应该等待图像加载事件触发?
    • 为什么“高度 = 高度 + 高度 // 将高度加倍以获得最佳效果”?
    【解决方案4】:

    如果动态添加媒体或使用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)
      })
    
    视频
    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)
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多