基于Jcrop的图片上传裁剪加预览

最近自己没事的时候研究了下图片上传,发现之前写的是有bug的,这里自己重新写了一个!

1、页面结构

DOCTYPE html>
<html lang="en"><head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit">
    <link rel="stylesheet" href="jquery.Jcrop.min.css">
<body>
<form method="post" id="uploadimg" name="uploadimg" action="" enctype="multipart/form-data" target="apply_iframe">
    <input type="file"  id="fileChange" style="color:#000" name="imageFileGuide"/>
form>
<div class="prew" style="width:300px;height:217px;background:#ccc;position:relative;">
    <img src="" id="target" width="100%" style="display:none;position:absolute;top:0;left:0;"/>
    <div id="filterPrew" style="display:none;position:absolute;top:0;left:0;">div>
    <img src="" id="filterPrewLoad" style="display:none;" />
div>
<label>X1坐标label><input type="text" size="4" id="x1" name="x1" />
<label>Y1坐标label><input type="text" size="4" id="y1" name="y1" />
<label>X2坐标label><input type="text" size="4" id="x2" name="x2" />
<label>Y2坐标label><input type="text" size="4" id="y2" name="y2" />
<label>裁剪的宽label><input type="text" size="4" id="w" name="w" />
<label>裁剪的高label><input type="text" size="4" id="h" name="h" />
<label>缩放比例label><input type="text" size="4" id="R" name="R" value="0"/>
body>
html>
<script src="jquery.min.js">script>
<script src="jquery.Jcrop.min.js">script>
<script src="upfile.js">script>
<script>

var dom = $('#fileChange')[0];
var prev = $('.prevw')[0];
szyFile.init(dom,prev,{'Ratio':1.2,'selectWidth':400,'selectHeight':300});

script>

js逻辑处理

var szyFile = {
    fileDom:null,//html 文件上传控件
    preview:null,//图片预览的区域
    imgMaxSize:2,//图片大小最大2M
    filterDom:[],//符合条件的元素
    filterImgDataUrl:[],//图片的dataUrl数据
    dragArea:null,//拖放区域
    jcrop_api:null,
    selectWidth:300,//选框宽度
    selectHeight:300,//选框高度
    Ratio:1,//上传图片比例
    imgRegExp:function(f){
        if(!/\.(jpg|jpeg|png)$/i.test(f.name)){
            alert('您上传的不是图片,请重新选择后上传!');
            return false;
        }
        return true;
    },
    clearCoords:function(){
         $('#coords input').val('');
    },
    showCoords:function(c){
        $('#x1').val(c.x);
        $('#y1').val(c.y);
        $('#x2').val(c.x2);
        $('#y2').val(c.y2);
        $('#w').val(c.w);
        $('#h').val(c.h);
    },
    jcropInit:function(ID){
        $(ID).Jcrop({
          onChange:   szyFile.showCoords,
          onSelect:   szyFile.showCoords,
          onRelease:  szyFile.clearCoords,
          aspectRatio: szyFile.Ratio,
          keySupport: false
        },function(){
          szyFile.jcrop_api = this;
        });
        $('#coords').on('change','input',function(e){
          var x1 = $('#x1').val(),
              x2 = $('#x2').val(),
              y1 = $('#y1').val(),
              y2 = $('#y2').val();
          szyFile.jcrop_api.setSelect([x1,y1,x2,y2]);
        });
    },
    isSupport:function(){
        if(window.File && window.FileReader && window.FileList && window.Blob) {
            return true;
        } else {
           return false;
        }
    },
    setPrew:function(w,h,ID,modle){
        var _top = 0;
        var _left = 0;
        if(w >= h){
            var imgB = szyFile.selectWidth/w;
            var imgB1 = w/h;
            if(h*imgB <= szyFile.selectHeight){
                $(ID).css('width',szyFile.selectWidth+'px');
                $(ID).css('height',h*imgB+'px');
                _top = ((szyFile.selectHeight-h*imgB)/2);
                _left = 0;
                $(ID).css('top',_top+'px');
                $(ID).css('left',_left+'px');
                $('#R').val(w/szyFile.selectWidth);
            }else{
                $(ID).css('width',szyFile.selectHeight*imgB1+'px');
                $(ID).css('height',szyFile.selectHeight+'px');
                _top = 0;
                _left = ((szyFile.selectWidth-szyFile.selectHeight*imgB1)/2);
                $(ID).css('top',_top+'px');
                $(ID).css('left',_left+'px');
                $('#R').val(h/szyFile.selectHeight);
            }
            szyFile.jcropInit(ID);
            $('.jcrop-holder').css({'position':'absolute','top':_top+'px','left':_left+'px'});
            if(modle == 0){
                $('.jcrop-tracker').css({'filter':'alpha(opacity=30); BACKGROUND-COLOR: white'});
            }
        }else{
            var imgB = szyFile.selectHeight/h;
            var imgB1 = h/w;
            if(w*imgB <= szyFile.selectWidth){
                $(ID).css('width',w*imgB+'px');
                $(ID).css('height',szyFile.selectHeight+'px');
                _top = 0;
                _left = (szyFile.selectWidth - w*imgB)/2;
                $(ID).css('top',_top+'px');
                $(ID).css('left',_left+'px');
                $('#R').val(h/szyFile.selectHeight);
            }else{
                $(ID).css('width',szyFile.selectWidth+'px');
                $(ID).css('height',szyFile.selectWidth*imgB1+'px');
                _top = (szyFile.selectHeight - szyFile.selectWidth*imgB1)/2;
                _left = 0;
                $(ID).css('top',_top+'px');
                $(ID).css('left',_left+'px');
                $('#R').val(w/szyFile.selectHeight);
            }
            szyFile.jcropInit(ID);
            $('.jcrop-holder').css({'position':'absolute','top':_top+'px','left':_left+'px'});
            if(modle == 0){
                $('.jcrop-tracker').css({'filter':'alpha(opacity=30); BACKGROUND-COLOR: white'});
            }
        }
    },
    select:function(e){
        var e = e || window.event;
        if(szyFile.isSupport()){
            if(szyFile.jcrop_api){
                szyFile.jcrop_api.destroy();
                $('#target').remove();
                $('').insertBefore('#filterPrew');
            }
            $('#target').show();
            $('#filterPrew').hide();
            var files = e.target.files || e.dataTransfer.files;
            for(var i = 0, f; f = files[i]; i++){
                if(f){
                    if(szyFile.imgRegExp(f)){
                        if(f.size > szyFile.imgMaxSize*1024*1024){
                            alert('图片过大,您上传的图片大于'+szyFile.imgMaxSize+'MB');
                            return false;
                        }else{
                            szyFile.filterDom.push(f);
                            var reader = new FileReader();
                            reader.onload = (function(){
                                return function(e){
                                    $('#target').attr('src',this.result);
                                    var resultImg = this.result;
                                    var img = new Image();
                                    img.onload = function(){
                                        var w = this.width;
                                        var h = this.height;
                                        szyFile.setPrew(w,h,'#target',1);
                                    }
                                    img.src = this.result;
                                };
                            })(f);
                            reader.readAsDataURL(f);
                        }
                    }
                }
            }
        }else{
            if(szyFile.jcrop_api){
                szyFile.jcrop_api.destroy();
                $('').insertAfter('#target');
            }
            $('#target').hide();
            $('#filterPrew').show();
            var src = $('#fileChange')[0].value;
            try {
                 var image = new Image();
                 image.dynsrc = src;
                 var filesize = image.fileSize;
             } catch (err) {
                 $('#fileChange')[0].select();
                 src = document.selection.createRange().text;
             }
            if(!/\.(jpg|jpeg|png)$/i.test(src)){
                alert('您上传的不是图片,请重新选择后上传!');
                return false;
            }
            $('#filterPrew').css('filter','none');
            $('#filterPrewLoad').css('filter','none');
            $('#filterPrew').css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = "scale", src="'+src+'")');
            $('#filterPrewLoad').css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = "image", src="'+src+'")');
            var w = $('#filterPrewLoad').width();
            var h = $('#filterPrewLoad').height();
            szyFile.setPrew(w,h,'#filterPrew',0);
        }
    },
    fileOnchange:function(elm){
        if(elm.addEventListener){
             elm.addEventListener('change', this.select, false);
        }else{
             elm.onchange = function(){
                szyFile.select();
             }
        }
    },
    fileValue:function(){
        return this.fileDom.value;
    },
    setRadio:function(num){
        if(num && num > 0){
            szyFile.Ratio = num;
        }
    },
    setSelectWidth:function(num){
        if(num && num > 0){
            szyFile.selectWidth = num;
        }
    },
    setSelectHeight:function(num){
        if(num && num > 0){
            szyFile.selectHeight = num;
        }
    },
    setImgMaxSize:function(num){
        if(num && num > 0){
            szyFile.imgMaxSize = num;
        }
    },
    init:function(dom,prev,config){
        if(config.imgMaxSize && config.imgMaxSize > 0){
            szyFile.imgMaxSize = config.imgMaxSize;
        }
        if(config.selectWidth && config.selectWidth > 0){
            szyFile.selectWidth = config.selectWidth;
        }
        if(config.selectHeight && config.selectHeight > 0){
            szyFile.selectHeight = config.selectHeight;
        }
        if(config.Ratio && config.Ratio > 0){
            szyFile.Ratio = config.Ratio;
        }
        if(dom) this.fileDom = dom;
        if(prev) this.preview = prev;
        this.fileOnchange(dom);
    }
}

 

代码调用如下


$(function(){

var dom = $('#fileChange')[0];
var prev = $('.prevw')[0];
szyFile.init(dom,prev,{'Ratio':1.2,'selectWidth':400,'selectHeight':300});


});

 附件下载地址:兼容IE6+ 以上大部分浏览器,特殊浏览器没有测试!

下载

你可能感兴趣的:(基于Jcrop的图片上传裁剪加预览)