1.实现说明
原文是开源中国上的一个demo,文章最后给出原文链接,上面有源码。实现框架是:maven+springmvc+jcrop。需要的主要js和css文件为jQuery.Jcrop.css,jquery.min.js,jquery.Jcrop.js。
2.一言不合上代码
2.1 controller层
import java.io.File;
import javax.servlet.http.HttpServletRequest;
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.multipart.MultipartFile;
@Controller
@RequestMapping("/UploadDemo")
public class UploadImgController {
@RequestMapping(value = "/uploadHeadImage",method = RequestMethod.POST)
public String uploadHeadImage(
HttpServletRequest request,
@RequestParam(value = "x") String x,
@RequestParam(value = "y") String y,
@RequestParam(value = "h") String h,
@RequestParam(value = "w") String w,
@RequestParam(value = "imgFile") MultipartFile imageFile
) throws Exception{
System.out.println("==========Start=============");
String realPath = request.getSession().getServletContext().getRealPath("/");
String resourcePath = "resources/uploadImages/";
if(imageFile!=null){
if(FileUploadUtil.allowUpload(imageFile.getContentType())){
String fileName = FileUploadUtil.rename(imageFile.getOriginalFilename());
int end = fileName.lastIndexOf(".");
String saveName = fileName.substring(0,end);
File dir = new File(realPath + resourcePath);
if(!dir.exists()){
dir.mkdirs();
}
File file = new File(dir,saveName+"_src.jpg");
imageFile.transferTo(file);
String srcImagePath = realPath + resourcePath + saveName;
int imageX = Integer.parseInt(x);
int imageY = Integer.parseInt(y);
int imageH = Integer.parseInt(h);
int imageW = Integer.parseInt(w);
//这里开始截取操作
System.out.println("==========imageCutStart=============");
ImgCut.imgCut(srcImagePath,imageX,imageY,imageW,imageH);
System.out.println("==========imageCutEnd=============");
request.getSession().setAttribute("imgSrc",resourcePath + saveName+"_src.jpg");//成功之后显示用
request.getSession().setAttribute("imgCut",resourcePath + saveName+"_cut.jpg");//成功之后显示用
}
}
return "success";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
2.2 两个工具类
文件上传工具类:
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class FileUploadUtil {
public static final List<String> ALLOW_TYPES = Arrays.asList(
"image/jpg","image/jpeg","image/png","image/gif"
);
//文件重命名
public static String rename(String fileName){
int i = fileName.lastIndexOf(".");
String str = fileName.substring(i);
return new Date().getTime()+""+ new Random().nextInt(99999999) +str;
}
//校验文件类型是否是被允许的
public static boolean allowUpload(String postfix){
return ALLOW_TYPES.contains(postfix);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
图片裁剪工具类:
import Java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import javax.imageio.ImageIO;
public class ImgCut {
/**
* 截取图片
* @param srcImageFile 原图片地址
* @param x 截取时的x坐标
* @param y 截取时的y坐标
* @param desWidth 截取的宽度
* @param desHeight 截取的高度
*/
public static void imgCut(String srcImageFile, int x, int y, int desWidth,
int desHeight) {
try {
Image img;
ImageFilter cropFilter;
BufferedImage bi = ImageIO.read(new File(srcImageFile+”_src.jpg”));
int srcWidth = bi.getWidth();
int srcHeight = bi.getHeight();
if (srcWidth >= desWidth && srcHeight >= desHeight) {
Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
cropFilter = new CropImageFilter(x, y, desWidth, desHeight);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(desWidth, desHeight,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
//输出文件
ImageIO.write(tag, “JPEG”, new File(srcImageFile+”_cut.jpg”));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.3 Jsp页面
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>demo</title>
<link rel="stylesheet" href="<c:url value="/resources/jcrop/css/jquery.Jcrop.css"/>" type="text/css"></link>
<script type="text/javascript" src="<c:url value="/resources/jcrop/js/jquery.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/jcrop/js/jquery.Jcrop.js"/>"></script>
</head>
<body>
<form name="form" action="<%=request.getContextPath()%>/UploadDemo/uploadHeadImage" class="form-horizontal" method="post" enctype="multipart/form-data">
<div class="modal-body text-center">
<div class="zxx_main_con">
<div class="zxx_test_list">
<input class="photo-file" type="file" name="imgFile" id="fcupload" onchange="readURL(this);" />
<img alt="" src="" id="cutimg" />
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
</div>
</div>
</div>
<div id="preview-pane">
<div class="preview-container">
<img src="" class="jcrop-preview" alt="预览">
</div>
</div>
<div class="modal-footer">
<button id="submit" onclick="">上传</button>
</div>
</form>
<script type="text/javascript">
//定义一个全局api,这样操作起来比较灵活
var api = null,
boundx,
boundy,
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(input.files[0]);
reader.onload = function(e) {
$('#cutimg').removeAttr('src');
$('#cutimg').attr('src', e.target.result);
$pimg.removeAttr('src');
$pimg.attr('src', e.target.result);
api = $.Jcrop('#cutimg', {
setSelect: [ 20, 20, 200, 200 ],
aspectRatio: 1,
onSelect: updateCoords,
onChange:updateCoords
});
var bounds = api.getBounds();
boundx = bounds[0];
boundy = bounds[1];
$preview.appendTo(api.ui.holder);
};
if (api != undefined) {
api.destroy();
}
}
function updateCoords(obj) {
$("#x").val(obj.x);
$("#y").val(obj.y);
$("#w").val(obj.w);
$("#h").val(obj.h);
if (parseInt(obj.w) > 0) {
var rx = xsize / obj.w;
var ry = ysize / obj.h;
$pimg.css({
width : Math.round(rx * boundx) + 'px',
height : Math.round(ry * boundy) + 'px',
marginLeft : '-' + Math.round(rx * obj.x) + 'px',
marginTop : '-' + Math.round(ry * obj.y) + 'px'
});
}
}
;
}
</script>
</body>
</html>
Jcrop 是一个功能强大的 jQuery 图像裁剪插件,结合后端程序(例如:PHP)可以快速的实现图片裁剪的功能。
此处有一个官方例子:http://code.ciaoca.com/jquery/jcrop/