JSFiddle - React, Tailwind, and code Playground
HTML
<input type="file" id="file"/>
JavaScript
$(document).on('change', '#file', function(evt){
processFile(this, evt);
});
function processFile(elem, evt){
if (!evt.srcElement.files[0].type.match('image.*')) {
alert('You can only attach images');
$(elem).val(null);
return;
}
var loading = $('<div>Loading...</div>');
$(elem).after(loading).hide();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
var maxWidth = $(elem).data('max_width') ? $(elem).data('max_width') : 640;
var maxHeight = $(elem).data('max_height') ? $(elem).data('max_height') : 420;
var previewWidth = $(elem).data('preview_width') ? $(elem).data('preview_width') : 300;
var reader = new FileReader();
reader.onloadend = function(evt, data) {
var img = new Image;
img.onload = function() {
var imageWidth = img.width;
var imageHeight = img.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
} else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
canvas.width = imageWidth;
canvas.height = imageHeight;
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
var finalFile = canvas.toDataURL("image/png");
$(elem).after('<img src="'+finalFile+'" width="'+previewWidth+'" />');
loading.remove();
};
img.src = evt.target.result;
};
reader.readAsDataURL(evt.srcElement.files[0]);
}