<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="cropper.css" rel="stylesheet">
<style type="text/css">
.container {
width: 400px;
height:400px;
}
</style>
</head>
<body>
<div class="container">
<img id="image" src="test.png">
</div>
<button type="button" onclick="uploadCropImg()">生成</button>
<script src="jquery.min.js"></script>
<script src="cropper.js"></script>
<script type="text/javascript">
$(document).ready(function (){
$(‘.container > img‘).cropper({
aspectRatio: 16 / 9,//截图比例
crop: function(data) {
// 出来裁切后的图片数据.
}
});
});
/* 上传裁剪之后的图片 **/
function uploadCropImg(){
var $image = $("#image");
var src = $image.eq(0).attr("src");
var canvasdata = $image.cropper("getCanvasData");
var cropBoxData = $image.cropper(‘getCropBoxData‘);
convertToData(src, canvasdata, cropBoxData, function (imgBase64Str){
imgBase64Str = imgBase64Str.replace("data:image/jpeg;base64," , "");
imgBase64Str = imgBase64Str.replace("data:image/png;base64," , "");
$.ajax({
type: "post",
url: "/项目名/imgCon/uploadCropImg.do",
data: {
imgBase64Str : imgBase64Str
},
success: function(data) {
if(data == "success"){
window.opener.cropImgSuccess();
}else{
alert("上传失败");
}
},error: function(request) {
alert("上传失败");
}
});
})
}
/* 把裁剪完之后的图片转成base64字符串 **/
function convertToData(url, canvasdata, cropdata, callback) {
var cropw = cropdata.width; // 剪切的宽
var croph = cropdata.height; // 剪切的宽
var imgw = canvasdata.width; // 图片缩放或则放大后的高
var imgh = canvasdata.height; // 图片缩放或则放大后的高
var poleft = canvasdata.left - cropdata.left; // canvas定位图片的左边位置
var potop = canvasdata.top - cropdata.top; // canvas定位图片的上边位置
var canvas = document.createElement("canvas");
var ctx = canvas.getContext(‘2d‘);
canvas.width = cropw;
canvas.height = croph;
var img = new Image();
img.src = url;
img.onload = function() {
this.width = imgw;
this.height = imgh;
// 这里主要是懂得canvas与图片的裁剪之间的关系位置
ctx.drawImage(this, poleft, potop, this.width, this.height);
var base64 = canvas.toDataURL(‘image/jpg‘, 1); // 这里的“1”是指的是处理图片的清晰度(0-1)之间,当然越小图片越模糊,处理后的图片大小也就越小
callback && callback(base64) // 回调base64字符串
}
}
</script>
</body>
</html>