There is an awesome library from blueimp that do what you want. You only need to import the library:
<script src="js/load-image.all.min.js"></script>
and set an event handler for the [onchange event][4] of the desired input, like this:
document.getElementById('file-input').onchange = function (e) {
var loadingImage = loadImage(
e.target.files[0],
function (img) {
document.body.appendChild(img);
},
{maxWidth: 600}
);
if (!loadingImage) {
// Alternative code ...
}
};
First param is a File or Blob object or just an image URL, the second is a callback that receives one HTML image element if everything was correct and you can resize, crop or manipulate the object returned with a map of options as third param of the loadImage function.
In this example e.target
is a reference to the object that dispatched the event. Take a look to the File API.
Important: For File or Blob objects as first param, this only works if browser supports URL API or FileReader.
Check the repo for more info: blueimp/JavaScript-Load-Image