Skip to content

Instantly share code, notes, and snippets.

@torgeir
Created March 25, 2015 12:16
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save torgeir/eab493939ec9cac1ad3f to your computer and use it in GitHub Desktop.
Save torgeir/eab493939ec9cac1ad3f to your computer and use it in GitHub Desktop.
React scaled file upload
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>
}
});
@zlove
Copy link

zlove commented May 23, 2018

Thanks @torgeir. Just what I was looking for.

@AndrewTkachenko
Copy link

AndrewTkachenko commented Dec 17, 2018

29 line - max_height should be maxHeight

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment