使用 JavaScript File API 获取图像尺寸

发布于 2024-12-05 07:33:04 字数 335 浏览 1 评论 0原文

我需要在我的网络应用程序中生成图像的缩略图。我使用 HTML5 File API 生成缩略图。

我使用了在 JavaScript 中读取文件 生成缩略图。

我能够成功生成缩略图,但我只能通过使用静态大小来生成缩略图。有没有办法从所选文件中获取文件尺寸,然后创建 Image 对象?

I require to generate a thumbnail of an image in my web application. I make use of the HTML5 File API to generate the thumbnail.

I made use of the examples from Read files in JavaScript to generate the thumbnails.

I am successfully able to generate the thumbnails, but I am able to generate thumbnail only by using a static size. Is there a way to get the file dimensions from the selected file and then create the Image object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

如痴如狂 2024-12-12 07:33:04

是的,将文件作为数据 URL 读取,并将该数据 URL 传递到 Imagesrchttp://jsfiddle.net/pimvdb/eD2Ez/2/

var fr = new FileReader;

fr.onload = function() { // file is loaded
    var img = new Image;

    img.onload = function() {
        alert(img.width); // image is loaded; sizes are available
    };

    img.src = fr.result; // is the data URL because called with readAsDataURL
};

fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating

Yes, read the file as a data URL and pass that data URL to the src of an Image: http://jsfiddle.net/pimvdb/eD2Ez/2/.

var fr = new FileReader;

fr.onload = function() { // file is loaded
    var img = new Image;

    img.onload = function() {
        alert(img.width); // image is loaded; sizes are available
    };

    img.src = fr.result; // is the data URL because called with readAsDataURL
};

fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
携余温的黄昏 2024-12-12 07:33:04

或者使用对象 URL:http://jsfiddle.net/8C4UB/

var url = URL.createObjectURL(this.files[0]);
var img = new Image;

img.onload = function() {
    alert(img.width);
    URL.revokeObjectURL(img.src);
};

img.src = url;

Or use an object URL: http://jsfiddle.net/8C4UB/

var url = URL.createObjectURL(this.files[0]);
var img = new Image;

img.onload = function() {
    alert(img.width);
    URL.revokeObjectURL(img.src);
};

img.src = url;
吃颗糖壮壮胆 2024-12-12 07:33:04

现有的答案对我帮助很大。然而,由于 img.onload 事件导致的奇怪的事件顺序让我的事情变得有点混乱。所以我调整了现有的解决方案,并将它们与基于承诺的方法结合起来。

下面是一个函数,返回一个带有维度作为对象的 Promise:

const getHeightAndWidthFromDataUrl = dataURL => new Promise(resolve => {
  const img = new Image()
  img.onload = () => {
    resolve({
      height: img.height,
      width: img.width
    })
  }
  img.src = dataURL
})

下面是如何将它与异步函数一起使用:

// Get a file from an input field
const file = document.querySelector('[type="file"]').files[0]

// Get the data URL of the image as a string
const fileAsDataURL = window.URL.createObjectURL(file)

// Get dimensions
const someFunction = async () => {
  const dimensions = await getHeightAndWidthFromDataUrl(fileAsDataURL)
  // Do something with dimensions ...
}

下面是如何使用 then() 语法来使用它:

// Get a file from an input field
const file = document.querySelector('[type="file"]').files[0]

// Get the data URL of the image as a string
const fileAsDataURL = window.URL.createObjectURL(file)

// Get the dimensions
getHeightAndWidthFromDataUrl(fileAsDataURL).then(dimensions => {
  // Do something with dimensions
})

The existing answers helped me a lot. However, the odd order of events due to the img.onload event made things a little messy for me. So I adjusted the existing solutions and combined them with a promise-based approach.

Here is a function returning a promise with the dimensions as an object:

const getHeightAndWidthFromDataUrl = dataURL => new Promise(resolve => {
  const img = new Image()
  img.onload = () => {
    resolve({
      height: img.height,
      width: img.width
    })
  }
  img.src = dataURL
})

Here is how you could use it with an async function:

// Get a file from an input field
const file = document.querySelector('[type="file"]').files[0]

// Get the data URL of the image as a string
const fileAsDataURL = window.URL.createObjectURL(file)

// Get dimensions
const someFunction = async () => {
  const dimensions = await getHeightAndWidthFromDataUrl(fileAsDataURL)
  // Do something with dimensions ...
}

And here is how you could use it using the then() syntax:

// Get a file from an input field
const file = document.querySelector('[type="file"]').files[0]

// Get the data URL of the image as a string
const fileAsDataURL = window.URL.createObjectURL(file)

// Get the dimensions
getHeightAndWidthFromDataUrl(fileAsDataURL).then(dimensions => {
  // Do something with dimensions
})
时光无声 2024-12-12 07:33:04

我已将 pimvdb 的答案 包装在一个函数中在我的项目中通用:

function checkImageSize(image, minW, minH, maxW, maxH, cbOK, cbKO) {
    // Check whether browser fully supports all File API
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        var fr = new FileReader;
        fr.onload = function() { // File is loaded
            var img = new Image;
            img.onload = function() { // The image is loaded; sizes are available
                if(img.width < minW || img.height < minH || img.width > maxW || img.height > maxH) {
                    cbKO();
                } else {
                    cbOK();
                }
            };
            img.src = fr.result; // Is the data URL because called with readAsDataURL
        };
        fr.readAsDataURL(image.files[0]);
    } else {
        alert("Please upgrade your browser, because your current browser lacks some new features we need!");
    }
}

I have wrapped pimvdb's answer in a function for general-purpose use in my project:

function checkImageSize(image, minW, minH, maxW, maxH, cbOK, cbKO) {
    // Check whether browser fully supports all File API
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        var fr = new FileReader;
        fr.onload = function() { // File is loaded
            var img = new Image;
            img.onload = function() { // The image is loaded; sizes are available
                if(img.width < minW || img.height < minH || img.width > maxW || img.height > maxH) {
                    cbKO();
                } else {
                    cbOK();
                }
            };
            img.src = fr.result; // Is the data URL because called with readAsDataURL
        };
        fr.readAsDataURL(image.files[0]);
    } else {
        alert("Please upgrade your browser, because your current browser lacks some new features we need!");
    }
}
不忘初心 2024-12-12 07:33:04
const img = new Image();
img.src = url;

console.log(img.width, img.height);

没什么花哨的,也能完成工作。

const img = new Image();
img.src = url;

console.log(img.width, img.height);

Nothing fancy and does the job.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文