javascript调整大小并预览多个图像,然后再上传

时间:2018-09-20 02:28:53

标签: javascript reactjs html5-canvas blob image-resizing

我是JS和React的新手。我正在使用React,并且我在一个表单中有多个文件输入,我希望如果用户选择图像,则应在用户单击上载之前调整图像的大小并进行预览。现在,调整大小,预览和上传都可以了,问题是当我更改文件输入时,其他文件输入的预览和上传都同步更改了!任何帮助将不胜感激。

这是代码:

render():

render(){
  return(
    ...
    <label>Image1
    <input type="file" id="img1" on Change={this.handleChange} />
    </label>
    <br/>
    <img id="img1_preview" src="" height="100" />
    <label>Image2
    <input type="file" id="img2" on Change={this.handleChange} />
    </label>
    <img id="img2_preview" src="" height="100" />
    ...
  )
}

function():

...
handleChange(event) {
  ...
  /* handle all image input change */
  if (event.target.id.includes('img')) {
    var field = event.target.id;
    var preview = document.getElementById(field + '_preview');
    var file = event.target.files[0];
    var reader = new FileReader();
    reader.onload = function(readerEvent) {
      var image = new Image();
      image.onload = function(imageEvent) {
        var canvas = document.createElement('canvas');
        var max_size = 800; /* max size */
        var width = image.width, height = image.height;
        if (width > height) {
          if (width > max_size) {
            height *= max_size / width;
            width = max_size;
          }
        } else {
          if (height > max_size) {
            width *= max_size / height;
            height = max_size;
          }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        /* Utility function to convert a canvas to a BLOB */
        var dataURLToBlob = function(dataURL) {
          var BASE64_MARKER = ';base64,';
          if (dataURL.indexOf(BASE64_MARKER) === -1) {
            var parts = dataURL.split(',');
            var contentType = parts[0].split(':')[-1];
            var raw = parts[1];
            return new Blob([raw],{type:contentType});
          }
          var parts = dataURL.split(BASE64_MARKER);
          var contentType = parts[0].split(':')[1];
          var raw = window.atob(parts[1]);
          var rawLength = raw.length;
          var uInt8Array = new Uint8Array(rawLength);
          for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
          }
          return new Blob([uInt8Array],{type:contentType});
        }
        /* End Utility function to convert a canvas to a BLOB */
        var resizedImage = dataURLToBlob(dataUrl);
        $.event.trigger({
          type: "imageResized",
          blob: resizedImage, 
          url: dataUrl
        });
      }
      image.src = readerEvent.target.result;
    }
    reader.readAsDataURL(file);
    $(document).on("imageResized",function(event1){
      if (event1.blob && event1.url) {
        var blob = event1.blob, url = event1.url;
        # set state, later will be submit to server
        this.setState({[field]:blob}); 
        /* preview */
        var reader1 = new FileReader();
        reader1.addEventListener("load",function(){
          preview.src = url;
        }, false);
        reader1.readAsDataURL(blob);
        /* end preview */
      }
    })
  }

页面: the page image

1 个答案:

答案 0 :(得分:0)

感谢@Kaiido,根据他的建议,问题已解决(尽管我不知道确切原因)。

这是工作代码:

...
handleChange(event) {
  ...
  /* handle all image input change */
  if (event.target.id.includes('img')) {
      var field = event.target.id;
      var preview = document.getElementById(field + '_preview');
      var file = event.target.files[0];
      var reader = new FileReader();
      reader.onload = function(readerEvent) {
      var image = new Image();
      image.onload = function(imageEvent) {
          var canvas = document.createElement('canvas');
          var max_size = 800; /* max size */
          var width = image.width, height = image.height;
          if (width > height) {
              if (width > max_size) {
                  height *= max_size / width;
                  width = max_size;
              }
          } else {
              if (height > max_size) {
                  width *= max_size / height;
                  height = max_size;
              }
          }
          canvas.width = width;
          canvas.height = height;
          canvas.getContext('2d').drawImage(image, 0, 0, width, height);
          var dataUrl = canvas.toDataURL('image/jpeg');
          /* changed code */
          canvas.toBlob(function(blob){
              this.setState({[field]:blob});
              var reader1 = new FileReader();
              reader1.addEventListener("load",function(){
                  preview.src = dataUrl;
              }, false);
              reader1.readAsDataURL(blob);
          });
          /* end changed */
      }
      image.src = readerEvent.target.result;
    }
    reader.readAsDataURL(file);
  }