根據用戶上傳的圖片,可以進行縮放裁剪並上傳到服務器
前臺需要引用兩個JS和一個css
JS CSS資源鏈接:http://pan.baidu.com/s/1kVA7B3D 密碼:1zkt
下面是完整 前臺代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>圖片裁剪</title>
<script type="text/javascript" src="editimg/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="editimg/js/cropbox.js"></script>
<link rel="stylesheet" type="text/css" href="editimg/css/style.css"/>
</head>
<body>
<div align="center">
<p style="color: red">
上傳成功後可能存在延遲,這是因爲瀏覽器緩存的問題,可清理緩存或稍等一會即可成功的替換圖片。
</p>
</div>
<div class="container" style="margin-left: 320px; margin-top: 20px;">
<div class="imageBox" style="width:700px;" >
<div class="thumbBox"></div>
<div class="spinner" style="display: none;">Loading...</div>
</div>
<div class="action" style="width: 700px;">
<input type="file" id="file" style="float:left; width: 250px;margin-left:-200px; display: none">
<input type="button" class="layui-btn layui-btn-small" onclick="clp()" value="選擇圖片" style="float: left;margin-top: 15px;margin-left:20px;">
<input type="button" class="layui-btn layui-btn-small" id="btnCrop" value="剪切並上傳" style="float: right; margin-top: 15px; margin-right:
20px;">
</div>
<div class="cropped"></div>
</div>
<script type="text/javascript">
function clp() {
return $("#file").click();
}
$(window).load(function () {
var options =
{
thumbBox: '.thumbBox',
spinner: '.spinner',
imgSrc: ''
}
// var cropper = $('.imageBox').cropbox(options);
$('#file').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
options.imgSrc = e.target.result;
cropper = $('.imageBox').cropbox(options);
}
reader.readAsDataURL(this.files[0]);
this.files = [];
})
$('#btnCrop').on('click', function () {
$(".cropped").empty();
var img = cropper.getDataURL();
$('.cropped').append('<img src="' + img + '">');
//點擊請求發送ajax請求
$.ajax({
url: "BannerImg",
data: { "data": img },
type: "post",
dataType: "json",
})
})
});
</script>
<div style="text-align:center;"></div>
</body>
</html>
!!上面綠色代碼需要根據自己JS CSS的路徑進行修改!!
ajax請求BannerImg的後臺代碼如下請查看我前篇文章
這個剪切圖片得到的是base64格式的圖片,我們需要將base64上傳到服務器保存