Resize image from input to upload

前端 未结 1 1912
庸人自扰
庸人自扰 2021-01-03 17:15

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 e

相关标签:
1条回答
  • 2021-01-03 18:12

    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);
    }
    
    0 讨论(0)
提交回复
热议问题