调整从输入到上传的图像大小

时间:2017-11-20 16:33:51

标签: javascript html5 reactjs

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

我的输入元素:

<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 before uploading尝试了这个解决方案,但这对我来说似乎不起作用。任何人都可以指出我的代码有什么问题以及如何修复它?非常感谢!

1 个答案:

答案 0 :(得分:2)

问题是您在访问图片widthheight之前没有等待图片加载。

在您等待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);
}