Home > Enterprise >  Get the width and height of an array of images angular typescript
Get the width and height of an array of images angular typescript

Time:08-15

I am uploading multiple images and before I upload I want to get the width and height of each image. The problem is that my function only returns the width and height of the first image only. Here's my code:

async getWidthAndHeight(files: any) {
    const newPromise = [files].map((file: any, i: any) => {
      return new Promise((resolve, reject) => {
        var reader = new FileReader();
        reader.readAsDataURL(file[i]);
        reader.onload = async (e: any) => {
          var image = new Image();
          image.src = e.target.result;
          image.onload = async () => {
            this.imageWidth = image.width;
            this.imageHeight = image.height;
            this.sizeObj = {
              width: this.imageWidth,
              height: this.imageHeight
            };
            resolve(this.sizeObj)
          }
        }
      })
    })
    const final = await Promise.all(newPromise);
    return final
  }

The return value is an array with the dimensions of the first image alone. I want the function to return the dimensions of all images. Any help would be greatly appreciated. Thanks!

CodePudding user response:

Considering your files as FileList use this to create array of promises and use file instead of file[i]

const newPromise = Array.from(files).map(file => {
  console.log(file);
  // your code
});
  • Related