Home > Mobile >  Wait for .onload and check resolution for multiple images
Wait for .onload and check resolution for multiple images

Time:09-28

User has a button where he can add multiple images. Now, I need to check every image resolution, and if all resolutions are above 800x600, then I need to upload images, otherwise, throw an error.

This need to look something like this:

prepareFilesList(files) {
  if (!this.verifyFilesResolution(files)) {
    this.selectedFiles = files; 
    this.uploadFiles();
  } else {
    return this.toastr.error('Image must be at least 800x600 .');
  }
 }

 verifyFilesResolution(files): boolean {
    let err = false;

    if (files && files.length > 0) {
      for (let i = 0; i < files.length; i  ) {
        let img = new Image();
  
        img.src = window.URL.createObjectURL(files[i]);
        img.onload = function () {

          if (img.width <= 800 || img.height <= 600) {
            err = true;
          }

        };
      }
    }

    return err;
  }

But, in this case, it doesn't work, because it doesn't wait for .onload and in all cases it throw an error. Somehow I need to wait for .onload and to loop trough all files or al least one where resolution isn't above 800x600.

How I can do this? Thank you.

CodePudding user response:

The onload function is called back asynchronously, so all your loop does as your code is written now is set up the callbacks, it won't ever wait for them to be done. You need something more like this (this is a general idea -- I haven't tested it):

prepareFilesList(files) {
  this.verifyFilesResolution(files, function(success) {
    if (success) {
      this.selectedFiles = files; 
      this.uploadFiles();
    } else {
      return this.toastr.error('Image must be at least 800x600 .');
    }
  }
}

 verifyFilesResolution(files, callback): boolean {
    let err = false;
    let imagesLoaded = 0;

    if (files && files.length > 0) {
      for (let i = 0; i < files.length; i  ) {
        let img = new Image();
  
        img.src = window.URL.createObjectURL(files[i]);
        img.onload = function () {
          if (img.width <= 800 || img.height <= 600) {
            err = true;
          }

          if (  imagesLoaded === files.length) {
            callback(!err);
          }
        };
      }
    }

    return err;
  }

Note: You should look into onerror and deal with failed image loads too.

  • Related