<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><html>
<head>
<title>Jsp开发头像裁剪</title>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.min.js"></script>
<script type="text/javascript" src="/js/ajaxfileupload.js"></script>
<style type="text/css">
*{margin: 0;padding: 0;}
.cut{
margin-top: 20px;
}
#preview-pane {
display: block;
position: absolute;
z-index: 2000;
top: 10px;
right: -480px;
padding: 6px;
border: 1px rgba(0,0,0,.4) solid;
background-color: white;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
}
#preview-pane .preview-container {
width: 250px;
height: 170px;
overflow: hidden;
}
</style>
<script type="text/javascript">
$(function(){
var jcrop_api,
boundx="",
boundy="",
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#cutImage').Jcrop({
onChange:showCoords,//获取选中的值
onSelect:showCoords,//获取拖拽的值
aspectRatio: xsize / ysize
},function(){
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
$('#imgW').val(boundx);
$('#imgH').val(boundy);
jcrop_api = this;
$preview.appendTo(jcrop_api.ui.holder);
});
function showCoords(c){
var x=c.x;
var y=c.y;
var w=c.w;
var h=c.h;
$("#x1").val(parseInt(x));
$("#y1").val(parseInt(y));
$("#w").val(parseInt(w));
$("#h").val(parseInt(h));
if (parseInt(c.w) > 0){
var rx = xsize / c.w;
var ry = ysize / c.h;
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
}
});
function uploadImg() {
$.ajaxFileUpload({
url:'/file/uploadImg',
secureuri:false,
fileElementId:'fileId',//file控件的id
dataType: 'json',//返回数据的类型
data:{},//一同上传的数据
success:function(data, status){
if (data.state == 1) {
var path = data.path;
$('#imgPath').val(path);
$("img").attr('src', path);
} else if (data.state == -1) {
alert('图片格式错误');
} else if (data.state == -2) {
alert('上传文件过大');
} else if (data.state == -3) {
alert('图片尺寸不正确');
} else {
alert('上传失败');
}
}
});
}
</script>
</head>
<body>
<h1>头像裁剪系统</h1>
<div class="cut">
<img id="cutImage" alt="" src="/imgs/timg.jpg" width="600">
<input type="file" id="fileId" name="ufile" class="absolute edithead_file" value="" οnchange="uploadImg()"/>
<div id="preview-pane">
<div class="preview-container">
<img src="/imgs/timg.jpg" class="jcrop-preview" alt="Preview" id="imageJcrop" />
</div>
</div>
</div>
<form action="/screenshot" method="post" >
<input type="hidden" name="imgPath" id="imgPath" value="/imgs/timg.jpg">
<input type="hidden" id="imgW" name="imgW" />
<input type="hidden" id="imgH" name="imgH" />
x轴:<input type="text" size="4" id="x1" name="x" />
y轴:<input type="text" size="4" id="y1" name="y"/>
宽度:<input type="text" size="4" id="w" name="w"/>
高度:<input type="text" size="4" id="h" name="h"/>
<input type="submit" value="裁剪"/>
</form>
</body>
</html>
ajax上传图片方法:
//img.path=D:/tomcat/8080/webapps/dspimg
//img.url=http://localhost:8080/dspimg
private static final String INPUT_NAME = "ufile"; //上传控件名
@Value("${img.path}")
private String imgpath; //文件服务器物理路径
@Value("${img.url}")
private String imgurl; //文件服务器访问路径
@Value("${img.ext}")
private String imgext; //可上传图片后缀,格式 *.bmp;*.gif;*.jpg;*.jpeg;*.png;
@Value("${img.maxsize}")
private String imgmaxsize; //图片最大多少k
/**
* 图片上传
* @param request
* @param width 限制宽
* @param height 限制高
* @param maxLength 限制大小,单位kb
* @param exts 可用后缀,格式: jpg,jpeg,png
* @return
*/
@ResponseBody
@RequestMapping("uploadImg")
public String uploadImg(HttpServletRequest request, Integer width, Integer height, Integer maxLength, String exts) {
FileBean fileBean = new FileBean();
/** 文件信息 **/
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile(INPUT_NAME);
String fileName = file.getOriginalFilename(); // 获得文件名
String ext = fileName.substring(fileName.lastIndexOf(".") + 1); // 后缀
//文件格式是否正确
if (!StringUtil.isBlank(exts)) {
if (exts.toLowerCase().indexOf(ext.toLowerCase()) == -1) {
log.error("图片格式错误");
fileBean.setState(-1);
return JsonUtil.json2Str(fileBean);
}
} else if (!validateImg(ext)) {
log.error("图片格式错误");
fileBean.setState(-1);
return JsonUtil.json2Str(fileBean);
}
Long fileSize = file.getSize();
//文件大小是否超标
if (maxLength != null && maxLength > 0) {
Long maxSize = (long) (maxLength * 1024.0);
if (fileSize > maxSize) {
log.error("文件大小超标");
fileBean.setState(-2);
return JsonUtil.json2Str(fileBean);
}
}
//获取图片属性
BufferedImage img = null;
try {
img = ImageIO.read(file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
int w = img.getWidth();
int h = img.getHeight();
//判断图片尺寸是否符合要求
if (width != null && height != null) {
if (w != width || h != height) {
log.error("图片尺寸不正确");
fileBean.setState(-3);
return JsonUtil.json2Str(fileBean);
}
}
/** 上传文件 **/
String newFileName = GlobalUtil.createFileName(ext); //新文件名
String newFilePath = imgpath + "/temp/" + newFileName; //新文件全路径
//创建目录
File pathDir = new File(imgpath + "/temp/");
if (!pathDir.exists()) {
pathDir.mkdirs();
}
//上传
File uploadFile = new File(newFilePath);
try {
FileCopyUtils.copy(file.getBytes(), uploadFile);
} catch (IOException e) {
e.printStackTrace();
}
/** 组装FileBean list **/
String newFileUrl = imgurl + "/temp/" + newFileName; //访问路径
fileBean.setPath(newFileUrl);
fileBean.setName(fileName);
fileBean.setNewName(newFileName);
fileBean.setExt(ext);
fileBean.setSize(fileSize);
fileBean.setSizeStr(CommonUtil.formatDataSize(file.getSize()));
fileBean.setWidth(w);
fileBean.setHeight(h);
//封装json对象
String jsonData = JsonUtil.json2Str(fileBean);
return jsonData;
}
/**
* @return 截图方法
*/
@RequestMapping(value = "screenshot", method = RequestMethod.POST)
public String screenshot(String imgPath,Integer x, Integer y, Integer w, Integer h,Integer imgW,Integer imgH) {
imgPath=imgPath.indexOf(imgurl)!=-1?imgPath:imgurl+imgPath;
ImageCut cut = new ImageCut();
UUser user = updateUfile(getSessionAdver(),imgPath.substring(imgPath.lastIndexOf("/")+1, imgPath.length()));
cut.cutImage(imgpath+user.getImg(),x,y,w,h,imgW,imgH);
put("userImg",imgurl+user.getImg());
return "/common/jcrop/image";
}
/**
* 获取图片新路径
* @param userId
* @param imgUrl
*/
public UUser updateUfile(UUser user, String imgHead) {
if (!StringUtil.isBlank(imgHead)) {
//保存头像
String tempPath = imgpath + "/temp/" + imgHead; //图片临时目录
String newRoot = imgpath + "/user/" + user.getId() + "/";
String newPath = newRoot + imgHead;
String savePath = "/user/" + user.getId() + "/" + imgHead;
File root = new File(newRoot);
try {
FileCopyUtils.copy(new File(tempPath), new File(newPath));
} catch (IOException e) {
e.printStackTrace();
}
user.setImg(savePath);
}
return user;
}
截图类
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics;
import javax.imageio.ImageIO;
public class ImageCut {
public void cutImage(String imagePath, int x ,int y ,int w,int h,int imgW,int imgH){
try {
Image img;
ImageFilter cropFilter;
// 读取源图像
BufferedImage bi = ImageIO.read(new File(imagePath));
int srcWidth = bi.getWidth(); // 源图宽度
int srcHeight = bi.getHeight(); // 源图高度
//若原图大小大于切片大小,则进行切割
if (srcWidth >= w && srcHeight >= h) {
Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
int x1 = x*srcWidth/imgW;
int y1 = y*srcHeight/imgH;
int w1 = w*srcWidth/imgW;
int h1 = h*srcHeight/imgH;
cropFilter = new CropImageFilter(x1, y1, w1, h1);
img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(w1, h1,BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // 绘制缩小后的图
g.dispose();
// 输出为文件
ImageIO.write(tag, "JPEG", new File(imagePath));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}