You need to use HTML5’s FileReader. Here,
image-fileis aninput type=filefile browser. If you need to restrict it to images or camera input:1<input type="file" accept="image/*" capture="camera" id="image-file" name="image-file" />When the user selects an image, bind a
changeevent to theinput fileto automatically read the local file.1 2 3 4 5 6 7var image_file = document.getElementById("image-file"); if (typeof FileReader === 'undefined') { image.innerHTML = "Sorry, your browser does not support FileReader"; image_file.setAttribute('disabled', 'disabled'); } else { image_file.addEventListener('change', readFile, false); }imageis animgtag with the idimage. ThereadFilefunction reads the image and automatically center-crops it to a width that adapts to the screen and a fixed height of 180px. The cropping process uses Canvas.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33function readFile() { var file = this.files[0]; if (!/image\/\w+/.test(file.type)) { alert("The file must be an image!"); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { var image = document.getElementById("image"); var img = new Image(); img.src = this.result; img.onload = function() { var x = 0, y = 0, width = img.width, height = img.height; if (img.width / window.innerWidth > img.height / 180) { width = window.innerWidth * img.height / 180; x = (img.width - width) / 2; } else { height = 180 * img.width / window.innerWidth; y = (img.height - height) / 2; } var canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = 180; var ctx = canvas.getContext('2d'); ctx.drawImage(img, x, y, width, height, 0, 0, canvas.width, canvas.height); var data = canvas.toDataURL(); image.innerHTML = '<img class="img-responsive" style="width:100%; height: 180px;" src="' + data + '" alt="" />'; } } }
Through these steps, the user can select an image, automatically read the local file, and then center-crop it to a width that adapts to the screen with a fixed height of 180px.