0

I was looking for a way to get the image size.

I learned that Promise and async/await can be used in image.onload.

Unlike many examples, however, I found that it works by simply awaiting null-state onload in code.

Why does this work well?

here's my code

  const base64 = reader.result;
  reader.onloadend = async () => {
        if (base64) {
          let img = new Image();
          img.src = base64.toString();
          await img.onload; // <-- null, Here's my question
          // img succesfully loaded.
        });
   ...
}

Add

Normal use method:

const base64 = reader.result;
  if (base64) {
  let img = new Image();
  img.src = base64.toString();
  img.onload = async () => {
    // setState or Do something.
  };

But I didn't specify any callback methods, but await waits until the image is loaded.

I wonder why you are waiting for me when onload is null.

Choiyos
  • 1
  • 1
  • Note that you don't need the FileReader here, you could rewrite it all as `for (let i = 0; i < e.target.files.length; i++) { const file = e.target.files[i]; this.selectedFileArray.push(file); const img = new Image(); img.src = URL.createObejctURL(file); await img.decode(); this.setState({ ...` – Kaiido Nov 09 '20 at 07:33
  • `bitmap = await createImageBitmap(file); var {width, height} = bitmap; bitmap.close();` – Endless Nov 09 '20 at 15:14

0 Answers0