最近项目需要上传用户图像,但是考虑到用户体验,需要提供用户裁剪功能,将裁剪好的图片上传服务器。
一开始百度裁剪图片插件,接触了jcrop,学习后发现它是提供图片的坐标、宽和高,然后去后台用java进行裁剪,
裁剪图片的效果并不怎么理想。后来换成cropper,该插件直接将裁剪好的图片转换成Base64上传,效果不错。
效果截图:
默认图像和选择文件按钮:
点击选择图片效果:
选中白衣服的柳岩:
点击确定按钮:
一:下载
cropper演示以及js、css文件下载地址:点击打开链接
二:导入js、css文件
<link rel="stylesheet" href="css/cropper.min.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/cropper.min.js"></script>
三:页面容器
<body>
<div class="upload">
<label title="上传图片" for="chooseImg" class="l-btn choose-btn">
<input type="file" name="file" id="chooseImg" class="hidden"
οnchange="selectImg(this)"> 选择图片
</label>
<div class="str">
<img id="finalImg" src="/demo/img/head.jpg" width="100%">
</div>
</div>
<!--图片裁剪框 start-->
<div style="display: none" class="tailoring-container">
<div class="black-cloth" οnclick="closeTailor(this)"></div>
<div class="tailoring-content">
<div class="tailoring-content-one">
<div class="close-tailoring" οnclick="closeTailor(this)">×</div>
</div>
<div class="tailoring-content-two">
<div class="tailoring-box-parcel">
<img id="tailoringImg">
</div>
<div class="preview-box-parcel">
<p>图片预览:</p>
<div class="square previewImg"></div>
<!-- <div class="circular previewImg"></div>-->
</div>
</div>
<div class="tailoring-content-three">
<button class="l-btn cropper-reset-btn">复位</button>
<button class="l-btn cropper-rotate-btn">旋转</button>
<button class="l-btn cropper-scaleX-btn">换向</button>
<button class="l-btn sureCut" id="sureCut">确定</button>
</div>
</div>
</div>
</body>
四:定义页面样式
<style>
* {
margin: 0;
padding: 0;
}
.l-btn {
display: inline-block;
outline: none;
resize: none;
border: none;
padding: 5px 10px;
background: #8C85E6;
color: #fff;
border: solid 1px #8C85E6;
border-radius: 3px;
font-size: 14px;
}
.l-btn:hover {
background: #8078e3;
animation: anniu 1s infinite;
}
.l-btn:active {
box-shadow: 0 2px 3px rgba(0, 0, 0, .2) inset;
}
.hidden {
display: none;
}
.tailoring-container, .tailoring-container div, .tailoring-container p {
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
.tailoring-container {
position: fixed;
width: 100%;
height: 100%;
z-index: 1000;
top: 0;
left: 0;
}
.tailoring-container .black-cloth {
position: fixed;
width: 100%;
height: 100%;
background: #111;
opacity: .9;
z-index: 1001;
}
.tailoring-container .tailoring-content {
position: absolute;
width: 768px;
height: 560px;
background: #fff;
z-index: 1002;
left: 0;
top: 0;
border-radius: 10px;
box-shadow: 0 0 10px #000;
padding: 10px;
}
.tailoring-content-one {
height: 40px;
width: 100%;
border-bottom: 1px solid #DDD;
}
.tailoring-content .choose-btn {
float: left;
}
.tailoring-content .close-tailoring {
display: inline-block;
height: 30px;
width: 30px;
border-radius: 100%;
background: #eee;
color: #fff;
font-size: 22px;
text-align: center;
line-height: 30px;
float: right;
cursor: pointer;
}
.tailoring-content .close-tailoring:hover {
background: #ccc;
}
.tailoring-content .tailoring-content-two {
width: 100%;
height: 460px;
position: relative;
padding: 5px 0;
}
.tailoring-content .tailoring-box-parcel {
width: 520px;
height: 450px;
position: absolute;
left: 0;
border: solid 1px #ddd;
}
.tailoring-content .preview-box-parcel {
display: inline-block;
width: 228px;
height: 450px;
position: absolute;
right: 0;
padding: 4px 14px;
}
.preview-box-parcel p {
color: #555;
}
.previewImg {
width: 200px;
height: 200px;
overflow: hidden;
}
.preview-box-parcel .square {
margin-top: 10px;
border: solid 1px #ddd;
}
.preview-box-parcel .circular {
border-radius: 100%;
margin-top: 10px;
border: solid 1px #ddd;
}
.tailoring-content .tailoring-content-three {
width: 100%;
height: 40px;
border-top: 1px solid #DDD;
padding-top: 10px;
}
.sureCut {
float: right;
}
@media all and (max-width: 768px) {
.tailoring-container .tailoring-content {
width: 100%;
min-width: 320px;
height: 460px;
}
.tailoring-content .tailoring-content-two {
height: 360px;
}
.tailoring-content .tailoring-box-parcel {
height: 350px;
}
.tailoring-container .tailoring-box-parcel {
width: 100%;
}
.tailoring-container .preview-box-parcel {
display: none;
}
}
.upload {
position: fixed;
right: 40rem;
top: 10rem;
}
.str {
width: 150px;
height: 140px;
border: solid 1px #e3e3e3;
padding: 5px;
margin-top: 10px
}
.tailoring-container {
width: 800px;
height: 800px;
}
</style>
五:js代码
<script type="text/javascript">
//弹出框水平垂直居中
(window.onresize = function() {
var win_height = $(window).height();
var win_width = $(window).width();
if (win_width <= 768) {
$(".tailoring-content").css(
{
"top" : (win_height - $(".tailoring-content")
.outerHeight()) / 2,
"left" : 0
});
} else {
$(".tailoring-content").css(
{
"top" : (win_height - $(".tailoring-content")
.outerHeight()) / 2,
"left" : (win_width - $(".tailoring-content")
.outerWidth()) / 2
});
}
})();
// 选择文件触发事件
function selectImg(file) {
//文件为空,返回
if (!file.files || !file.files[0]) {
return;
}
$(".tailoring-container").toggle();
var reader = new FileReader();
reader.onload = function(evt) {
var replaceSrc = evt.target.result;
// 更换cropper的图片
$('#tailoringImg').cropper('replace', replaceSrc, false);// 默认false,适应高度,不失真
}
reader.readAsDataURL(file.files[0]);
}
// cropper图片裁剪
$('#tailoringImg').cropper({
aspectRatio : 1 / 1,// 默认比例
preview : '.previewImg',// 预览视图
guides : false, // 裁剪框的虚线(九宫格)
autoCropArea : 0.5, // 0-1之间的数值,定义自动剪裁区域的大小,默认0.8
movable : false, // 是否允许移动图片
dragCrop : true, // 是否允许移除当前的剪裁框,并通过拖动来新建一个剪裁框区域
movable : true, // 是否允许移动剪裁框
resizable : true, // 是否允许改变裁剪框的大小
zoomable : false, // 是否允许缩放图片大小
mouseWheelZoom : false, // 是否允许通过鼠标滚轮来缩放图片
touchDragZoom : true, // 是否允许通过触摸移动来缩放图片
rotatable : true, // 是否允许旋转图片
crop : function(e) {
// 输出结果数据裁剪图像。
}
});
// 旋转
$(".cropper-rotate-btn").on("click", function() {
$('#tailoringImg').cropper("rotate", 45);
});
// 复位
$(".cropper-reset-btn").on("click", function() {
$('#tailoringImg').cropper("reset");
});
// 换向
var flagX = true;
$(".cropper-scaleX-btn").on("click", function() {
if (flagX) {
$('#tailoringImg').cropper("scaleX", -1);
flagX = false;
} else {
$('#tailoringImg').cropper("scaleX", 1);
flagX = true;
}
flagX != flagX;
});
// 确定按钮点击事件
$("#sureCut").on("click", function() {
if ($("#tailoringImg").attr("src") == null) {
return false;
} else {
var cas = $('#tailoringImg').cropper('getCroppedCanvas');// 获取被裁剪后的canvas
var base64 = cas.toDataURL('image/jpeg'); // 转换为base64
$("#finalImg").prop("src", base64);// 显示图片
uploadFile(encodeURIComponent(base64))//编码后上传服务器
closeTailor();// 关闭裁剪框
}
});
// 关闭裁剪框
function closeTailor() {
$(".tailoring-container").toggle();
}
//ajax请求上传
function uploadFile(file) {
$.ajax({
url : '/demo/upload.do',
type : 'POST',
data : "file=" + file,
async : true,
success : function(data) {
console.log(data)
}
});
}
</script>
六:后台java代码
package com.debo.cropper;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("upload")
public class Cropper {
/**
* 注释的代码可以忽略
* @throws
*/
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String cropper(@RequestParam("file") String file,
HttpServletRequest request) throws Exception {
Decoder decoder = Base64.getDecoder();
// 去掉base64编码的头部 如:"data:image/jpeg;base64," 如果不去,转换的图片不可以查看
file = file.substring(23);
//解码
byte[] imgByte = decoder.decode(file);
/*//在tomcat目录下创建picture文件夹保存图片
String path = request.getSession().getServletContext()
.getRealPath("");
String contextPath = request.getContextPath();
path = path.replace(contextPath.substring(1), "") + "picture";
File dir = new File(path);
if (!dir.exists()) {// 判断文件目录是否存在
dir.mkdirs();
}
//因为windows和linux路径不同,window:D:\dir linux:opt/java
//System.getProperty("file.separator")能根据系统的不同获取文件路径的分隔符
String fileName = getFileName();
path = path + System.getProperty("file.separator") + fileName;
*/
try {
FileOutputStream out = new FileOutputStream("D:/1.jpg"); // 输出文件路径
out.write(imgByte);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return "success";
/*String url = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + "/picture/" + fileName;
return url; */
}
/**
* 创建文件名称 内容:时间戳+随机数
*
* @param @return
* @throws
*/
private String getFileName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timeStr = sdf.format(new Date());
String str = RandomStringUtils.random(5,
"abcdefghijklmnopqrstuvwxyz1234567890");
String name = timeStr + str + ".jpg";
return name;
}
}
RandomStringUtils需要导入依赖
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>