Skip to content

Instantly share code, notes, and snippets.

@AdreeUA
Forked from torgeir/react-scaled-file-upload.js
Created February 24, 2017 18:29
Show Gist options
  • Select an option

  • Save AdreeUA/d52bc9adacf7cf62475c127a23dea189 to your computer and use it in GitHub Desktop.

Select an option

Save AdreeUA/d52bc9adacf7cf62475c127a23dea189 to your computer and use it in GitHub Desktop.

Revisions

  1. @torgeir torgeir created this gist Mar 25, 2015.
    85 changes: 85 additions & 0 deletions react-scaled-file-upload.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,85 @@

    function resize (file, maxWidth, maxHeight, fn) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (event) {
    var dataUrl = event.target.result;

    var image = new Image();
    image.src = dataUrl;
    image.onload = function () {
    var resizedDataUrl = resizeImage(image, maxWidth, maxHeight, 0.7);
    fn(resizedDataUrl);
    };
    };
    }

    function resizeImage(image, maxWidth, maxHeight, quality) {
    var canvas = document.createElement('canvas');

    var width = image.width;
    var height = image.height;

    if (width > height) {
    if (width > maxWidth) {
    height = Math.round(height * maxWidth / width);
    width = maxWidth;
    }
    } else {
    if (height > max_height) {
    width = Math.round(width * maxHeight / height);
    height = maxHeight;
    }
    }

    canvas.width = width;
    canvas.height = height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, width, height);
    return canvas.toDataURL("image/jpeg", quality);
    }

    var ScalingUpload = React.createClass({

    getInitialState: function () {
    return {};
    },

    _onChange: function (e) {
    var files = e.target.files;
    var self = this;
    var maxWidth = this.props.maxWidth;
    var maxHeight = this.props.maxHeight;
    resize(files[0], maxWidth, maxHeight, function (resizedDataUrl) {
    self.setState({ dataUrl: resizedDataUrl });
    });
    },

    render: function () {
    var image;

    var dataUrl = this.state.dataUrl;
    if (dataUrl) {
    image = <img src={dataUrl} />
    }

    return <div>
    <input ref="upload" type="file" accept="image/*" onChange={ this._onChange }/>
    { image }
    </div>
    }
    });

    var Test = React.createClass({

    _onChange: function (file) {
    console.log('done', file);
    },

    render: function () {
    return <div>
    <ScalingUpload maxHeight={100} maxWidth={100} onChange={ this._onChange } />
    </div>
    }
    });