Java如何实现图片裁剪预览功能

时间:2021-10-25 10:25:43

在项目中,我们需要做些类似头像上传,图片裁剪的功能,ok看下面文章!
需要插件:jQuery Jcrop
后端代码:

?
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
58
59
60
package org.csg.upload;
 
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class Upload {
 /**
  * @author 小夜的传说
  * @param path1 图片原路径
  * @param path2 裁剪后存储的路径
  * @param x x轴
  * @param y y轴
  * @param w
  * @param h
  */
 public static void CutImage(String path1,String path2,int x,int y,int w,int h){
  FileInputStream fileInputStream=null;
  ImageInputStream iis=null;
   
  try {
   //读取图片文件,建立文件输入流
   fileInputStream=new FileInputStream(path1);
   //创建图片的文件流 迭代器
   Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader reader=it.next();
   //获取图片流 建立文图 文件流
   iis=ImageIO.createImageInputStream(fileInputStream);
   //获取图片默认参数
   reader.setInput(iis, true);
   ImageReadParam param=reader.getDefaultReadParam();
   //定义裁剪区域
   Rectangle rect=new Rectangle(x,y,w,h);
   param.setSourceRegion(rect);
   BufferedImage bi=reader.read(0,param);
   ImageIO.write(bi, "jpg", new File(path2));
  } catch (Exception e) {
   e.printStackTrace();
   System.out.println("裁剪失败");
  }finally{
   try {
    if(fileInputStream!=null){
     fileInputStream.close();
    }
    if(iis!=null){
     iis.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
    
  }
 }
}

访问代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" import="java.util.*,org.csg.upload.*" pageEncoding="utf-8"%>
<%
 //图片的相对路径
 String imagPath=request.getParameter("imgPath");
 String relPath=request.getRealPath("/");//获取图片服务器绝对地址
 String newFileName=new Date().getTime()+".jpg";
 //实际图片路径
 String path1=relPath+imagPath;
 //裁剪后存储到服务器的图片路径
 String path2=relPath+"/images/"+newFileName;
  
 int x=Integer.parseInt(request.getParameter("x"));
 int y=Integer.parseInt(request.getParameter("y"));
 int w=Integer.parseInt(request.getParameter("w"));
 int h=Integer.parseInt(request.getParameter("h"));
 try{
 Upload.CutImage(path1, path2, x, y, w, h);
 out.print("<img src='images/"+newFileName+"'/>");
 }catch(Exception e){
 e.printStackTrace();
 out.print("图片裁剪失败");
 }
%>

jsp代码:

?
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <title>Jsp开发头像裁剪</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
 <script type="text/javascript" src="js/jquery.min.js"></script>
 <script type="text/javascript" src="js/jquery.Jcrop.min.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: -280px;
   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];
     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'
     });
     }
    }
   });
  </script>
 </head>
 <body>
 <h1>Java开发QQ头像裁剪系统</h1>
 <div class="cut">
  <img id="cutImage" alt="" src="images/1.jpg" >
  <div id="preview-pane">
   <div class="preview-container">
    <img src="images/1.jpg" class="jcrop-preview" alt="Preview" />
   </div>
  </div>
 </div>
 <form action="success.jsp" method="post" >
  <input type="text" value="images/1.jpg" name="imgPath">
  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>

效果图:

Java如何实现图片裁剪预览功能

以上就是本文的全部内容,希望大家能够喜欢。