1. 程式人生 > >使用jcrop擷取指定大小的圖片

使用jcrop擷取指定大小的圖片

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"/>