迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中获取图像尺寸

作者:迹忆客 最近更新:2024/03/16 浏览次数:

有时,在将图像上传到托管服务器或使用它之前,我们可能需要检查或验证图像的尺寸,即图像的高度和宽度。我们可能需要检查其尺寸以调整大小、裁剪或更改图像。

我们可以使用 JavaScript 轻松地做到这一点。

在本文中,我们将学习如何使用 JavaScript 获取图像的尺寸或检查图像的高度和宽度。


在 JavaScript 中使用 widthheight 属性获取图像尺寸

我们可以使用 JavaScript 中的 widthheight 属性快速获取图像的尺寸。下面的程序将向我们展示这一点。

var i = new Image();
i.src =
    'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/2560px-Image_created_with_a_mobile_phone.png';
i.onload = function() {
  alert(this.width + 'x' + this.height);
}

输出:

我们使用 new Image() 构造函数在上面的程序中创建了一个图像对象。然后,Image() 构造函数创建了一个新的图像元素实例。

然后使用图像 URL 源添加 i.src 图片,并使用 i.onload() 方法确定图像的高度和宽度。

然而,这个程序只显示页面上呈现的 img 元素的大小,而不是图像的自然高度和宽度。


在 JavaScript 中使用 naturalWidthnaturalHeight 获取图像尺寸

在处理图像尺寸时,始终强烈建议我们计算出图像的真实宽度和高度。

因此,我们将考虑使用 naturalWidthnaturalHeight 属性来使用 JavaScript 检索图像的确切尺寸。

naturalWidthnaturalHeight 是只读属性,它们用于找出图像的原始宽度和高度。

我们可能会使用 img 标签的 widthheight 元素来更改我们网页上显示的图像的高度和宽度。naturalWidthnaturalHeight 属性用于需要图像的原始宽度或高度的情况。

<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Find Real Image Width and Height</title>
<script>
    function imgSize(){
        var myImg = document.querySelector("#sky");
        var realWidth = myImg.naturalWidth;
        var realHeight = myImg.naturalHeight;
        alert("Original width=" + realWidth + ", " + "Original height=" + realHeight);
    }
</script>
</head>
<body>
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/2560px-Image_created_with_a_mobile_phone.png" id="sky" width="250" alt="Cloudy Sky">
    <p><button type="button" onclick="imgSize();">Get Original Image Size</button></p>
</body>
</html>

输出:

在使用这种方法时,我们可能会得到非常不一致的结果。在直接找到图像的尺寸之前考虑这两种情况也很重要。

图像可能没有被获取,在这种情况下尝试获取尺寸会给我们错误的输出。

首先,我们必须确保图像已加载。我们还需要检查图像是否从浏览器的缓存中加载。

问题源于内部,即 JavaScript 运行时。如果 JavaScript 在该图像完全下载和渲染之前运行,则结果将为 0。

但是,如果 JavaScript 在图像下载和渲染后运行,结果将是正确的。

<html>
    <head>
        <title>Title of the Document</title>
        <style>
            img {
                margin: 20px;
            }
        </style>
    </head>
    <body>
        <div>Click on img to see the result</div>
        <script>
            let img = document.createElement('img');
            img.id = 'imgId';
            img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/2560px-Image_created_with_a_mobile_phone.png';
            document.body.appendChild(img);
            img.addEventListener("click", imgSize);
            function imgSize() {
                let img = document.getElementById('imgId');
                let width = img.clientWidth;
                let height = img.clientHeight;
                alert("Original width=" + width + ", " + "Original height=" + height);
            }
        </script>
    </body>
</html>i.addEventListener('load', function() {
    console.log('Width: ', this.naturalWidth);
    console.log('Height: ', this.naturalHeight);
});

此链接将提供上述示例中使用的代码。

我们能做的最低限度是在测量之前确保图像已经加载。图像完成后会发出一个 load 事件,你可以使用回调来进行测量。

我们还将进行一些错误处理,因为图像可以发出一个 error 事件。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便