美文网首页
Html5本地图片读取及裁剪

Html5本地图片读取及裁剪

作者: Cesium中文网 | 来源:发表于2018-09-18 15:54 被阅读0次
  1. 需要使用到Html5的FileReader,其中image-file是一个input type=file的文件浏览框。如果需要限制读取图片或者照相机:
<input type="file" accept="image/*" capture="camera" id="image-file" name=" image-file" />
  1. 当用户选择了图片之后,给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);
}
  1. 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");
 
        var image=new Image();
        image.src = this.result;
        var x = 0, y = 0, width = image.width, height = image.height;
        if (image.width / $(window).width() > 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=$('<canvas width="'+width+'" height="'+height+'"></canvas>')[0],
        ctx=canvas.getContext('2d');
        ctx.drawImage(image,x,y,width,height,0,0,width,height);
        var data=canvas.toDataURL();
 
        image.innerHTML = '<img class="img-responsive" style="width:100%; height: 180px;" src="'+data+'" alt=""/>'
    }
}

相关文章

网友评论

      本文标题:Html5本地图片读取及裁剪

      本文链接:https://www.haomeiwen.com/subject/ycspnftx.html