css部分:
.add-pic{position: relative;width: 220px; height: 220px;overflow: hidden; display:block;}
#clipArea {
margin: 20px;
height: 240px;
width: 240px;
overflow: hidden;
}
#file{ position: absolute;top:0px;left: 0px;padding-left: 240px; height:260px; display: block; margin-top: -10px; margin-left: -10px;background: rgba(0,0,0,0.0);}
#view {
border-radius: 5px;
overflow: hidden;
margin: 0 auto;
width: 220px;
height: 220px;
}
#view img{
display: block;
width: 100%;
height: 100%;
}
html部分:
<a class='add-pic'>
<div id="clipArea" style='display:none;'></div>
<input type="file" id="file" name="is">
<form method="post" encType="multipart/form-data"></form>
<button id="clipBtn" style='display:none;'>截取</button>
<div id="view">
<img id="addLogo" src="image/add-pic.png" alt="">
</div>
</a>
js部分:
引入文件(4个),如下:
<script src='js/jquery-1.11.2.min.js'></script>
<script src='js/jquery.form.js'></script>
<script src='js/iscroll-zoom.js'></script>
<script src='js/jquery.photoClip.js'></script>
代码:
$("#clipArea").photoClip({
width: 126,
height: 126,
/*按宽高比例来截取图片*/
/*strictSize: false,*/
file: "#file",
view: "#view",
ok: "#clipBtn",
loadStart: function() {
},
loadComplete: function() {
$("#clipBtn").click();
},
clipFinish: function(dataURL) {
var dataStr=dataURL;
convertToFile(dataStr);
function convertToFile(base64Codes){//将base64转化blob,并放到form中
var form=document.forms[0];
var formData = new FormData(form);
var img_name=$("#file").val();
formData.append("is",convertBase64UrlToBlob(base64Codes),img_name);//img是input的name属性,与后台的对应即可
$.ajax({//提交表单,异步上传图片
url : "http://120.26.237.229:18080/pchat-ling/app/uploadImg?",
type : "POST",
data : formData,
dataType:"json",
processData : false, // 告诉jQuery不要去处理发送的数据
contentType : false, // 告诉jQuery不要去设置Content-Type请求头
success:function(result){
$("#addLogo").attr("src",result.data.url);
}
});
}
function convertBase64UrlToBlob(urlData){
var bytes=window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob( [ab] , {type : 'image/png'});
}
}
});
注释:
1、 width: 126, height: 126,为自动裁剪图片大小;
效果图:
上传前:
上传后: