项目需要做一个头像截取的功能,类似于QQ头像截取功能。在网上搜了下,最后使用jQuery插件jcrop来截取,
在后台来进行图片切割。
头像截取的原理:在前台使用jcrop获取切面的x轴坐标、y轴坐标、切面高度、切面宽度,然后将这四个值传给后台。在后台要进行放大处理:将切面放大N倍,
N=原图/前台展示的头像。
即X = X*原图宽/前图宽,
Y = Y*原图高/前 图高,
W = W*原图宽/前图宽,
H = H*原图高/前图高。
根据上一篇博客的知识,完成了项目中头像裁剪上传的功能
<link rel="stylesheet" href="css/jquery.Jcrop.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.Jcrop.js"></script>
<div style="padding-left: 120px">
<img
<c:choose>
<c:when test="${!empty sessionScope.com_crm_auth_entity_Admin.photo }">
src="<%=request.getContextPath()%>/resources/uploadImages/${sessionScope.com_crm_auth_entity_Admin.photo}"
</c:when>
<c:otherwise>src="<%=basePath %>static/img/user.png"</c:otherwise>
</c:choose>
id="userImg" height="80" style="background-color: #fff; border: 1px solid #ddd; border-radius: 4px;
-webkit-transition: all .2s ease-in-out; -o-transition: all .2s ease-in-out; transition: all .2s ease-in-out;"
title="点击更换头像" style="cursor: pointer;" onclick="changeImg(1);"/>
</div>
<!-- 修改头像开始 -->
<div class="jc-demo-box" id="cPhoto" style="display: none;margin-left: 20px;">
<form name="form" class="form-inline" role="form" id="cpFrom"
action="<%=request.getContextPath()%>/uploadImg/uploadHeadImage"
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=""
<c:choose>
<c:when test="${!empty sessionScope.com_crm_auth_entity_Admin.photo }">
src="<%=request.getContextPath()%>/resources/uploadImages/${sessionScope.com_crm_auth_entity_Admin.photo}"
</c:when>
<c:otherwise>src="<%=basePath %>static/img/user.png"</c:otherwise>
</c:choose>
id="cutimg" width="400px" height="270px"/>
<input type="hidden" id="uid" name="uid" value="${sessionScope.com_crm_auth_entity_Admin.id}"/>
<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" >
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" onclick="uploadImg();">上传</button>
<button type="button" class="btn btn-warning" onclick="changeImg();">关闭</button>
</div>
</form>
</div>
<!-- 修改头像结束 -->
<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
});
/* getBounds() 获取图片实际尺寸,格式为:[w,h]
getWidgetSize() 获取图片显示尺寸,格式为:[w,h]
getScaleFactor() 获取图片缩放的比例,格式为:[w,h] */
var bounds = api.getBounds();
boundx = bounds[0];
boundy = bounds[1];
$preview.appendTo(api.ui.holder);
var obj={};
obj.x=20;obj.y=20;obj.w=180,obj.h=180;obj.x2=200;obj.y2=200;
updateCoords(obj);
};
/* 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'
});
}
}
;
}
function changeImg(sign){
if(sign==1){
$("#cPhoto").show();
}else{
$("#cPhoto").hide();
}
}
function uploadImg(){
var imageFile=$("#fcupload").val();
var x=$("#x").val();
var y=$("#y").val();
var w=$("#w").val();
var h=$("#h").val();
if (imageFile == null || imageFile == undefined || imageFile == '') {
alert("请选择一张图片再上传!");
} else{
$("#cpFrom").submit();
}
}
</script>
后台处理图片,并上传
package com.crm.common.controller;
@Controller
@RequestMapping("/uploadImg")
public class UploadImgController {
@Autowired
private AdminService adminService;
@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 = "uid") String id,
@RequestParam(value = "imgFile") MultipartFile imageFile
) {
try {
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=============");
String imgCut = ImgCut.imgCut(srcImagePath,imageX,imageY,imageW,imageH);
System.out.println("==========imageCutEnd============="+imgCut);
Map<String, String> map=new HashMap<String, String>();
map.put("id", id);
map.put("photo", imgCut);
int updateId = adminService.updatePhoto(map);
if(updateId>0){
Admin admin = adminService.selectByUid(updateId);
//将用户信息存入session
request.getSession().removeAttribute(WebKeys.ADMINUSER_KEY);
request.getSession().setAttribute(WebKeys.ADMINUSER_KEY, admin);
}
}
}
} catch (Exception e) {
}
return "common/changePhoto";
}
}
裁剪工具类
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 java.io.IOException;
import javax.imageio.ImageIO;
public class ImgCut {
/**
*
* 截取图片
*
* @param srcImageFile
* 原图片地址
* @param x
* 截取时的x坐标
* @param y
* 截取时的y坐标
* @param desWidth
* 截取的宽度
* @param desHeight
* 截取的高度
* @return desImageName 截取之后的图片的名字
* @throws IOException
*/
public static String imgCut(String srcImageFile, int x, int y, int desWidth,
int desHeight) throws IOException {
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);
//将图片按照一定比例显示出来,但是传递到后台的时候需要经历一个比例换算 此处的400和270与前台设定的一致
int x1 = x*srcWidth/400;
int y1 = y*srcHeight/270;
int w1 = desWidth*srcWidth/400;
int h1 = desHeight*srcHeight/270;
cropFilter = new CropImageFilter(x1, y1, w1, h1);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
// BufferedImage tag = new BufferedImage(desWidth, desHeight,
// BufferedImage.TYPE_INT_RGB);
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(srcImageFile + "_photo.jpg"));
}
return srcImageFile.substring(srcImageFile.lastIndexOf("/")+1) + "_photo.jpg";
}
}
FileUploadUtil.java
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);
}
}