Problem in image size validation

Asked

Viewed 134 times

0

In my application I make a preview of the image, this part is ok, but the client wants to validate the dimensions before the upload. At first it would also be ok, if it were that in a few moments the FileReader cannot grasp the dimensions of the image, returning the height and width worthwhile 0. Someone’s been through it?

I’m using the Angular 7.2

readerFile(files, input) {
  const img = new Image();
  img.src = window.URL.createObjectURL( files[0] );

  const reader = new FileReader();

  this.setImage(files[0]);
  this.imagePath = files;

  this.onloadReaderFile(reader, img, input, files);
}

onloadReaderFile(reader: FileReader, img, input, files) {
  reader.readAsDataURL(files[0]);

  reader.onload = (event) => {
    const width = img.naturalWidth;
    const height = img.naturalHeight;

    window.URL.revokeObjectURL( img.src );

    if (!this.isReaderFileWithSuccess(height, width, input)) {
      return;
    }
    if (!this.isCorrectSizeImage(height, width, input)) {
      return;
    }

    this.isNewImage = true;
    this.imgURL = reader.result;
  };
}

isReaderFileWithSuccess(height: number, width: number, input: HTMLInputElement): boolean {
  if (height === 0 && width === 0 ) {
    this.message = 'Erro ao importar o arquivo, tente novamente!';
    input.value = '';
    this.removeImage();
    return false;
  }
  return true;
}

I even put an error message warning the problem, but he does not want to give this problem.

Note: Often this error does not occur at first try, on my computer I need to keep changing the images after several attempts occurs this problem.

  • So I noticed the problem is time to create the image and not in FileReader, but I still don’t know what it could be

1 answer

0


I was able to solve this problem by adding onload in the image also, nor did he know that this method existed on the type object Image, in the end only the method readerFile was modified and ended up like this:

readerFile(files, input) {
  const img = new Image();
  img.src = window.URL.createObjectURL(files[0]);

  const reader = new FileReader();

  this.setImage(files[0]);
  this.imagePath = files;

  img.onload = () => { // Adicionado isso
    this.onloadReaderFile(reader, img, input, files);
  };
}

What was causing this anomaly is that I wasn’t expecting the object Image finished opening and using the actual file and was already using the FileReader. How I did the validation of the image size inside the onload of FileReader, sometimes it occurred that it ended before the Image and give the validation problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.