首页 » Web开发 » 正文

[HTML5]Html5本地图片读取及裁剪

  1. 需要使用到Html5的FileReader,其中image-file是一个input type=file的文件浏览框。如果需要限制读取图片或者照相机:
    <input type="file" accept="image/*" capture="camera" id="image-file" name=" image-file" />
    
  2. 当用户选择了图片之后,给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);
    }
    
  3. image就是一个id为image的img标签。readFile函数将图片读入,并自动居中裁剪为 宽度自适应屏幕,高度固定为180px的图片。裁剪的过程中需要使用Canvas。

    function readFile(){
    var file = this.files[0];
    if(!/image\/\w+/.test(file.type)){
        alert(&quot;文件必须为图片!&quot;);
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e){
        var image = document.getElementById(&quot;image&quot;);</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() &amp;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=$('&amp;lt;canvas width=&amp;quot;'+width+'&amp;quot; height=&amp;quot;'+height+'&amp;quot;&amp;gt;&amp;lt;/canvas&amp;gt;')[0],
    ctx=canvas.getContext('2d');
    ctx.drawImage(image,x,y,width,height,0,0,width,height);
    var data=canvas.toDataURL();
    
    image.innerHTML = '&amp;lt;img class=&amp;quot;img-responsive&amp;quot; style=&amp;quot;width:100%; height: 180px;&amp;quot; src=&amp;quot;'+data+'&amp;quot; alt=&amp;quot;&amp;quot;/&amp;gt;'
    </code></pre>
    
    <p>}
    }
    

发表评论