-
需要使用到Html5的FileReader,其中
image-file是一个input type=file的文件浏览框。如果需要限制读取图片或者照相机:1<input type="file" accept="image/*" capture="camera" id="image-file" name="image-file" /> -
当用户选择了图片之后,给
input file绑定change事件,自动读取本地文件。1 2 3 4 5 6 7var image_file = document.getElementById("image-file"); if (typeof FileReader === 'undefined') { image.innerHTML = "抱歉,你的浏览器不支持 FileReader"; image_file.setAttribute('disabled', 'disabled'); } else { image_file.addEventListener('change', readFile, false); } -
image就是一个id为image的img标签。readFile函数将图片读入,并自动居中裁剪为宽度自适应屏幕,高度固定为180px的图片。裁剪的过程中需要使用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("文件必须为图片!"); 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="" />'; } } }
通过以上步骤,用户可以选择图片并自动读取本地文件,然后将图片居中裁剪为宽度自适应屏幕,高度固定为180px的图片。