springMVC+jcrop实现头像上传截图功能
<!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(); ?
??????? } ?
??? }
}
總結
以上是生活随笔為你收集整理的springMVC+jcrop实现头像上传截图功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 免重装系统更换AHCI磁盘驱动器模式
- 下一篇: c++倒计时