- 需要使用到Html5的FileReader,其中image-file是一个input type=file的文件浏览框。如果需要限制读取图片或者照相机:
<input type="file" accept="image/*" capture="camera" id="image-file" name=" image-file" />
- 当用户选择了图片之后,给input file绑定change事件,自动读取本地文件。
var 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。
function 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");</p> <pre><code>var image=new Image(); image.src = this.result; var x = 0, y = 0, width = image.width, height = image.height; if (image.width / $(window).width() &gt; image.height / 180) { width = $(window).width() * image.height / 180; x = (image.width - width) / 2; } else { height = 180 * image.width / $(window).width(); y = (image.height - height) / 2; } var canvas=$('&lt;canvas width=&quot;'+width+'&quot; height=&quot;'+height+'&quot;&gt;&lt;/canvas&gt;')[0], ctx=canvas.getContext('2d'); ctx.drawImage(image,x,y,width,height,0,0,width,height); var data=canvas.toDataURL(); image.innerHTML = '&lt;img class=&quot;img-responsive&quot; style=&quot;width:100%; height: 180px;&quot; src=&quot;'+data+'&quot; alt=&quot;&quot;/&gt;' </code></pre> <p>} }