1

I've been struggled with this problem for couple hours. I want to resize an image from an input tag and then upload it to the server. Here is my attempt.

My input element:

<Input type="file" name="file" onChange={this.handleLoadAvatar} />

My handleLoadAvatar function:

handleLoadAvatar(e) {
var file = e.target.files[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = (e) => {
  img.src = e.target.result;
}
reader.readAsDataURL(file);

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

var MAX_WIDTH = 300;
var MAX_HEIGHT = 300;
var width = img.width; // GET STUCK HERE
var height = img.height;

if (width > height) {
  if (width > MAX_WIDTH) {
    height *= MAX_WIDTH / width;
    width = MAX_WIDTH;
  }
} else {
  if (height > MAX_HEIGHT) {
    width *= MAX_HEIGHT / height;
    height = MAX_HEIGHT;
  }
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
this.setState({previewSrc: dataurl});

}

I'm using ReactJS for my project. I got stuck at the line with the comment above where I can't get the image's width. I tried this solution at HTML5 Pre-resize images before uploading but this seems not to work for me. Can anybody point out what's wrong with my code and how to fix it? Thanks a bunch!

Rogerio Schmitt
  • 1,055
  • 1
  • 15
  • 35
TungPham
  • 103
  • 3
  • 13
  • 1
    Could you check this https://stackoverflow.com/questions/23945494/use-html5-to-resize-an-image-before-upload to resolve the issue – vickisys Nov 20 '17 at 16:41

1 Answers1

6

The problem is that you aren't waiting for the image to load before accessing its width and height.

As you are waiting for the reader, you should do the same for the img:

handleLoadAvatar(e) {
  var file = e.target.files[0];
  var reader = new FileReader();
  reader.onload = (e) => {
    var img = document.createElement("img");
    img.onload = () => {
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);

      var MAX_WIDTH = 300;
      var MAX_HEIGHT = 300;
      var width = img.width;
      var height = img.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }
      canvas.width = width;
      canvas.height = height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, width, height);
      var dataurl = canvas.toDataURL("image/png");
      this.setState({previewSrc: dataurl});
    }
    img.src = e.target.result;
  }
  reader.readAsDataURL(file);
}
Maluen
  • 1,753
  • 11
  • 16