天天看點

圖檔剪裁

最近使用者上傳的頭像需要剪裁,要适配手機和pc端。花了點時間終于搞定了,廢話不多說,效果圖走一波。

圖檔剪裁
圖檔剪裁
圖檔剪裁
圖檔剪裁

OK頭像上傳成功。 上面就是整個效果啦。接下來介紹具體實作 關鍵代碼走起

<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>

<script src="js/iscroll-zoom.js"></script>
<script src="js/hammer.js"></script>
<script src="js/lrz.all.bundle.js"></script>
<script src="js/jquery.photoClip.js"></script>
</head>
<body>
<input type="file" id="upfile">
<img id="img">
 <!-- 圖檔處理 -->
    <div id="img_screen" style="position:absolute;top:0;width:100%;background:#000;overflow:hidden;display:none;"></div>
    <div id="img_box" style="position:absolute;top:0;width:100%;display:none;margin-top:20%;">
		<div id="clipArea" style="margin:20px;height: 300px;"></div>
    </div>
    <button id="clipBtn0" style="position:absolute;top:20px;right:50;border:0;color:#fff;background:#000;display:none;font-size: 16px;">    取消</button>
    <button id="clipBtn" style="position:absolute;top:20px;right:0;border:0;color:#fff;background:#000;display:none;font-size: 16px;">确定    </button>
<!-- end -->
</body>
<script type="text/javascript">
$("#upfile").change(function(){
    var objUrl=getObjectURL(this.files[0])
    if(objUrl){
        $(window).scrollTop(0);
        $("section").hide();
        $("#img_screen").show();              
        $("#img_box").show();              
        $("#clipBtn").show();
        $("#clipBtn0").show();
        var M=parseInt(this.files[0].size/1024000);
    	//if(M>=1)layer.open({content: '您的圖檔超過了'+M+'M,正在讀取...',skin: 'msg',time: 2});
        //else layer.open({content: '正在讀取圖檔,請耐心等待...',skin: 'msg',time: 2});
    }
})

function getObjectURL(file){
	var url=null 
	if(window.createObjectURL!=undefined){ // basic
	    url=window.createObjectURL(file)
	}else if(window.URL!=undefined){ // mozilla(firefox)
		url=window.URL.createObjectURL(file)
	} else if(window.webkitURL!=undefined){ // webkit or chrome
		url=window.webkitURL.createObjectURL(file)
	}
	return url;
}
$("#img_screen").css("height",$(window).height())
    var clipArea = new bjj.PhotoClip("#clipArea", {
		size: [250, 250],
		file: "#upfile",	    
		ok: "#clipBtn",	   
        clipFinish: function(dataURL) {
        	$("#img_screen").hide();              
        	$("#img_box").hide();              
        	$("#clipBtn").hide();      
        	$("#clipBtn0").hide();    
        	$("#img").attr("src",dataURL);
		}
    })
</script>
           

如果還有疑問的話,或者需要完整demo的可以直接聯系我的qq:1913284695.