从输入调整图像大小以上传

IT技术 javascript html reactjs
2021-05-10 11:12:49

我一直在努力解决这个问题几个小时。我想从输入标签调整图像大小,然后将其上传到服务器。这是我的尝试。

我的输入元素:

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

我的handleLoadAvatar功能:

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});

}

我在我的项目中使用 ReactJS。我被困在上面的注释行中,我无法获得图像的宽度。在上传之前HTML5 Pre-resize images 上尝试了这个解决方案,但这似乎对我不起作用。谁能指出我的代码有什么问题以及如何修复它?谢谢一堆!

1个回答

问题是您在访问其width之前没有等待图像加载height

当您在等待 时reader,您应该对 做同样的事情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);
}