73

我需要在我的 Web 应用程序中生成图像的缩略图。我使用 Html 5 File API 来生成缩略图。

我利用以下 URL 中的示例来生成缩略图。

http://www.html5rocks.com/en/tutorials/file/dndfiles/

我成功地生成了缩略图。我遇到的问题是我只能通过使用静态大小来生成缩略图。有没有办法从选定的文件中获取文件尺寸,然后创建 Image 对象?

4

4 回答 4

147

是的,将文件作为数据 URL 读取并将该数据 URL 传递srcImage: 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
于 2011-09-18T08:19:03.890 回答
35

或者使用对象 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;
于 2013-06-24T10:09:36.273 回答
14

现有的答案对我帮助很大。然而,由于事件的奇怪顺序img.onload让事情对我来说有点混乱。所以我调整了现有的解决方案,并将它们与基于承诺的方法相结合。也许这对其他人有帮助。

这是一个函数返回一个以维度作为对象的承诺:

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
})
于 2020-10-08T18:46:48.573 回答
5

我在我的项目中将 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() { // 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!");
    }
}    
于 2014-12-15T17:56:01.187 回答