在回调-javascript上获取上传的图像高度和宽度

时间:2018-02-22 01:10:19

标签: javascript reactjs callback

我需要从文件字段异步加载多个图像,并检查尺寸是否有效。我非常接近,我只需要在回调时获得先前加载的图像的高度。到目前为止,这是我的努力:

let  files = this.fileUpload.files; //get all uploaded files 
   for (var i = 0, f; f = files[i]; i++) { //iterate over uploaded file
      console.log(f);
      let img = new Image();
      img.name=f.name;
      img.size=f.size;



       img.onload = () =>{alert(img.height)} //it is giving height here

      if (img.complete) { //callback 
           alert(img.name + 'loaded');
           load_count++;
           library_store.uploaded_image.push(
                                              {
            height:img.height,
            width:img.width, // not coming, just wondering how to get 
                             //the image height from load
            name:img.name,
            size:img.size
                                              }
                                           );
 }
if(load_count === uploaded_file_count){ // if all files are loaded
 //do all validation here , I need height and width here 
}

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

您不想将library_store逻辑移至img.onload吗?如下所示:

let  files = this.fileUpload.files; //get all uploaded files 
for (var i = 0, f; f = files[i]; i++) { //iterate over uploaded file
    console.log(f);
    let img = new Image();
    img.name=f.name;
    img.size=f.size;

    img.onload = function() {
        // hoping that ```this``` here refers to ```img```
        alert(this.name + 'loaded');
        load_count++;
        library_store.uploaded_image.push({
            height:this.height,
            width:this.width,
            name:this.name,
            size:this.size
        });

        if(load_count === uploaded_file_count){ // if all files are loaded
            //do all validation here , I need height and width here 
        }
    }

    // img.onload = () =>{alert(img.height)} //it is giving height here
    /*
    if (img.complete) { //callback 
        alert(img.name + 'loaded');
        load_count++;
        library_store.uploaded_image.push({
            height:img.height,
            width:img.width,
            name:img.name,
            size:img.size
        });

        if(load_count === uploaded_file_count){ // if all files are loaded
        //do all validation here , I need height and width here 
        }
    }
    */
}

答案 1 :(得分:1)

首先,让我们看看为什么即使您的图片尚未加载,您仍将永远属于此if(img.complete)块:

HTMLImageElement的complete属性仅告知在获取属性时是否正在加载其资源。

如果加载成功,失败则会报告true,如果src尚未设置,则会报告

var img = new Image();
console.log('no-src', img.complete);
img.onerror = function() {
  console.log('in-error', img.complete);
  img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=="
};
img.onload = function() {
  console.log('in-load', img.complete);
}
img.src = "/some/fake-path.png";
console.log('while loading', img.complete);

而且,当您获得此属性时,您尚未设置此src属性,因此即使您的图片尚未加载其资源,它也会报告true

所以你想要的是一个图像预加载器:

function preloadImages(srcArray, mustAllSucceed) {
  return Promise.all(srcArray.map(loadImage));

  function loadImage(src) {
    return new Promise((resolve, reject) => {
      var img = new Image();
      img.onload = success;
      img.onerror = mustAllSucceed ? success : reject;
      img.src = src;

      function success() {
        resolve(img)
      };
    });
  }
}
preloadImages(['https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg', 'https://upload.wikimedia.org/wikipedia/commons/9/9b/Gran_Mezquita_de_Isfah%C3%A1n%2C_Isfah%C3%A1n%2C_Ir%C3%A1n%2C_2016-09-20%2C_DD_34-36_HDR.jpg'])
  .then(images => {
    images.forEach(img => console.log(img.src, img.width, img.height));
  }, true);