使用Javascript File API获取图像尺寸

Abi*_*hek 49 javascript thumbnails fileapi

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

我使用了以下URL中的示例来生成缩略图.

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

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

pim*_*vdb 117

是的,阅读文件作为数据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
Run Code Online (Sandbox Code Playgroud)

  • `img.onload = function(){`永远不会触发 (4认同)
  • img.onload是Image上onload事件的处理程序,只有在加载某些东西后才被调用。在这种情况下,img.src = fr.result;将触发onload事件。语义上,您希望事件处理程序绑定之前,事件可能会触发。如果onload没有触发,请尝试img.onerror = function(err){console.error(err); },以查看文件读取器是否无法加载Image可以处理的内容。(或者如果出现其他问题) (3认同)
  • 在`img.onload`之前做`img.src = fr.result;` (2认同)

let*_*aik 18

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

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

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

img.src = url;
Run Code Online (Sandbox Code Playgroud)

  • 通常最好在 `onload` 处理程序中撤销 url:`URL.revokeObjectURL(url)`。 (4认同)
  • 此方法不会将图像加载到内存中.readAsDataURL.http://stackoverflow.com/questions/6217652/html5-file-api-crashes-chrome-when-using-readasdataurl-to-load-a-selected-image (3认同)

sam*_*sam 12

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

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

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

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

// 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 ...
}
Run Code Online (Sandbox Code Playgroud)

下面是如何使用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
})
Run Code Online (Sandbox Code Playgroud)

  • 我在互联网上找到的唯一相关答案。非常感谢先生ヽ( ̄д ̄)ノ (4认同)

小智 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!");
    }
}    
Run Code Online (Sandbox Code Playgroud)