使用jcrop截取指定大小的图片

来源:互联网 发布:贺福初是谁的女婿知乎 编辑:程序博客网 时间:2024/06/06 00:22

1、到http://deepliquid.com/content/Jcrop.html网站上下载jcrop包,将css、demo_files包添加到项目中,如下图所示:

2、selectfile.jsp的代码如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="utf-8"%>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.Jcrop.js"></script>
<script type="text/javascript">
  jQuery(function($){
 var jcrop_api,
        boundx,
        boundy,

        // Grab some information about the preview pane
        $preview = $('#preview-pane'),
        $pcnt = $('#preview-pane .preview-container'),
        $pimg = $('#preview-pane .preview-container img');

    
    $('#srcImg').Jcrop({
      aspectRatio:1,
   onChange:showCoords,
   onSelect:showCoords,
   minSize:[200,200]
    },function(){
      // Use the API to get the real image size
      var bounds = this.getBounds();
      boundx = bounds[0];
      boundy = bounds[1];
      // Store the API in the jcrop_api variable
      jcrop_api = this;

      // Move the preview into the jcrop container for css positioning
      $preview.appendTo(jcrop_api.ui.holder);
    });
 function showCoords(obj){
  $("#x").val(obj.x);
  $("#y").val(obj.y);
  $("#w").val(obj.w);
  $("#h").val(obj.h);
  if(parseInt(obj.w)>0){
    //计算预览区域图片缩放的比例,通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到  
               var rx = 200 / obj.w; 
               var ry = 200 / obj.h; 
                //通过比例值控制图片的样式与显示  
               $('#preview-pane .preview-container img').css( { 
                  width : Math.round(rx * $("#srcImg").width()) + "px", //预览图片宽度为计算比例值与原图片宽度的乘积  
                    height : Math.round(ry* $("#srcImg").height()) + "px", //预览图片高度为计算比例值与原图片高度的乘积  
                    marginLeft : "-" + Math.round(rx * obj.x) + "px", 
                    marginTop : "-" + Math.round(ry * obj.y) + "px" 
               });
  }
  }

  });
  function changeImg(){
  document.forms[0].submit();
  }

 
</script>
<link rel="stylesheet" href="demo_files/main.css" type="text/css" />
<link rel="stylesheet" href="demo_files/demos.css" type="text/css" />
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />
<style type="text/css">

.jcrop-holder #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: 200px;
  height: 200px;
  overflow: hidden;
}
</style>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="cache-control" content="no-cache">

<title>top</title>
</head>
<body>&nbsp;
 
 获取图片: 
  <div id="cutImage" >
  <div class="bigImg" >   
     <form action="<%=request.getContextPath() %>/upload" method="post" enctype="multipart/form-data">
  上传文件:<input type="file" name="file1" id="sf" onchange="changeImg();"/><br/>
  <!-- <input type="submit" value="提交"><br/> -->
 </form>
 <%
 String path=(String)request.getSession().getAttribute("imageUrl");
 if(path!=null){
 out.println(path);
 %> 
 <img alt="" src="<%=path %>" width="30%" height="30%" id="srcImg" >
 <div id="preview-pane">
    <div class="preview-container">
      <img src="<%=path %>" class="jcrop-preview" alt="Preview" />
    
    </div>
    </div>
 <%
 }
  %>
  </div> 
    </div>
   
   
     <form action="<%=request.getContextPath() %>/UpdatePhoto" method="post" name="crop_form" >
  <input type="hidden" id="bigImg" name="bigImage" value="<%=path %>"/>
  <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" />
  <p><input type="submit" value="保存" id="crop_submit" /></p>
 </form>
  预览图片:
    <%
    String str=(String)request.getParameter("url");
    out.print(str);
    if(str!=null){
    %>
    <div id="preview_box" class="previewImg"  >
  <img id="previewImg" src="../upload/<%=str %>?tempid=<%=Math.random() %>" name="previewImg"/>
 </div>
    <%
    }
    %>
 
</body>
</html>

3、切割图片的java代码:

package com.jcrop;

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 ImageCut {
/***
 * 图片切割
 * @param imagePath 原图地址
 * @param x 目标切片坐标 x轴起点
 * @param y 目标切片坐标 y轴起点
 * @param w 目标切片  宽度
 * @param h 目标切片 高度
 */
 public String cutImage(String imagePath,int x,int y,int w,int h){
  Image img;
  ImageFilter cropFilter;
  
  try {
   //读取源图像
   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/400;
//    int y1=y*srcHeight/270;
//    int w1=w*srcWidth/400;
//    int h1=h*srcHeight/270;
    int x1=x;
    int y1=y;
    int w1=w;
    int h1=h;
    
    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_BGR);
    Graphics g=tag.getGraphics();
    g.drawImage(img, 0, 0, null);
    g.dispose();
    
    String url=imagePath.substring(0,imagePath.lastIndexOf("\\")+1);
    String name=imagePath.substring(imagePath.lastIndexOf("\\")+1);
    System.out.println(name);
    String[] src=name.split("\\.");
    imagePath=src[0].concat("cut.").concat(src[1]);
    url=url.concat(imagePath);
    System.out.println(imagePath);
    
    ImageIO.write(tag, "JPEG",new File(url) );
    
   }
   
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return imagePath;
 }
}

4、将生成的图片返回到selectfile.jsp页面的java类

package com.jcrop;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UpdatePhoto extends HttpServlet {


 public UpdatePhoto() {
  super();
 }


 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }


 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {  
 } 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  int x=Integer.valueOf(request.getParameter("x"));
  int y=Integer.valueOf(request.getParameter("y"));
  int w=Integer.valueOf(request.getParameter("w"));
  int h=Integer.valueOf(request.getParameter("h"));
  String bigImage=request.getParameter("bigImage");
  String[] imageNames=bigImage.split("/");
  String imageName=imageNames[imageNames.length-1];
  String imagePath=getServletContext().getRealPath("upload");
//  String imagePath=request.getContextPath()+"\\"+imageName;
  imagePath=imagePath+"\\"+imageName;
  ImageCut imageCut=new ImageCut();
  String url=imageCut.cutImage(imagePath, x, y, w, h);
  System.out.println("url:"+url);
  //request.setAttribute("url", url);
  //System.out.println("xxxxxx"+request.getAttribute("url"));
  
  response.sendRedirect("jcrop/selectfile.jsp?url="+url);
  doGet(request, response);
 }


 public void init() throws ServletException {
  // Put your code here
 }

}

5、效果如下:

                

 

补充问题

 使用ie8浏览器加载图片时,若图片改变,名字不变,浏览器会加载之前的照片,若显示当前照片需要刷新

解决办法:在图片的路径后加上随机参数,即:<img id="previewImg" src="../upload/<%=str %>?tempid=<%=Math.random() %>" name="previewImg"/> 

原创粉丝点击