http://blog.csdn.net/u012547633/article/details/39553833
//这次是根据上次的,完成图片切割
---------------------------------------------------------jsp------------------------------------------------------------------
//需要的js
<link rel="stylesheet" href="<%=basePath%>view/common/img/main.css" type="text/css" />
<link rel="stylesheet" href="<%=basePath%>view/common/img/demos.css" type="text/css" />
<link rel="stylesheet" href="<%=basePath%>view/common/img/jquery.Jcrop.css" type="text/css" />
</head>
<body style="padding:0px">
<script type="text/javascript" src="<%=basePath%>view/jsp/admin/system/attachment_manager.js"></script>
<script type="text/javascript" src="<%=basePath%>view/common/img/jquery.Jcrop.js"></script>
//页面,点击处理图片弹窗
<div id="tool" style="padding:5px;height:auto;overflow: hidden;">
<input type="file" id="fileId" name="uploadFileName" />
<input type="button" id="buttonId" value="图片处理" /><br />
处理后图片id:<input type="text" size="20" id="cutId" name="cutId" value="" />
</div>
<div id="window" class="easyui-window" title="图片处理上传" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:873px;height:600px;padding:10px;">
<div class="container">
<div class="row">
<div class="span12">
<div class="jc-demo-box">
<img id="target" src="#" onclick="initimage($);" alt="[Jcrop Example]" />
<form id="applyForm" class="coords">
<div class="inline-labels">
<label>源:<input type="text" id="srcImageFile" name="srcImageFile" value="" /></label><br />
<label>X <input type="text" size="4" id="x" name="x" /></label>
<label>Y <input type="text" size="4" id="y" name="y" /></label>
<label>X2 <input type="text" size="4" id="x2" name="x2" /></label>
<label>Y2 <input type="text" size="4" id="y2" name="y2" /></label>
<label>destWidth <input type="text" size="4" id="destWidth" name="destWidth" /></label>
<label>destHeight <input type="text" size="4" id="destHeight" name="destHeight" /></label>
</div>
</form>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
<div style="text-align:center;padding:5px">
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">提交</a>
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()">关闭</a>
</div>
</div>
-----------------------------------------------------------------js--------------------------------------------------------------------------------
//清空表单,并关闭弹窗
function clearForm(){
$('#applyForm').form('clear');
$('#window').window('close');
}
//打开并居中窗口
function openWindow(){
clearForm();
$('#window').window('open');
$('#window').window('center');
}
/**
* 验证上传文件框里是否为null
*/
$(function () {
$("#buttonId").click(function () {
if ($("#fileId").val().length > 0) {
ajaxFileUpload();
}
else {
$.messager.alert("请选择文件!");
}
});
});
/**
* ajax异步提交文件
* 将保存的文件信息Id返回
* @returns {Boolean}
*/
function ajaxFileUpload() {
$.ajaxFileUpload({
url: uploadUrl, //用于文件上传的服务器端请求地址
secureuri: false, //一般设置为false
fileElementId: 'fileId', //文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'json', //返回值类型 一般设置为json
type:"post",
success: function (data,status){
if(data.result=="typeError") {
$.messager.alert("提示信息","上传类型错误!","waring");
} else {
//get图片添加服务器路径
$("#target").attr("src",basepath+data.result.aPath);
$('#applyForm').form('load',{
//添加服务器 地址
srcImageFile:data.result.aPath,
});
}
},
});
openWindow();
return false;
}
//提交保存表单
function submitForm(){
if(!$("#applyForm").form('validate'))return;
$.ajax({
url: imageCut,
data:$("#applyForm").serialize(),
success: function (data,status){
if(data.result=="typeError") {
$.messager.alert("提示信息","上传类型错误!","waring");
} else {
//将ID返回给文本框
$("#cutId").attr("value",data.result.id);
alert(data.result.id);
}
}
});
clearForm();
$('#window').window('close');
}
///页面切割图片/
/**
* 初始化切片
* @param $
*/
function initimage($){
var jcrop_api;
$('#target').Jcrop({
onChange: showCoords,
onSelect: showCoords,
onRelease: clearCoords,
minSize:[400,300],
maxSize:[400,300]
},function(){
jcrop_api = this;
});
$('#coords').on('change','input',function(e){
var x1 = $('#x').val(),
x2 = $('#x').val(),
y1 = $('#y1').val(),
y2 = $('#y2').val();
jcrop_api.setSelect([x1,y1,x2,y2]);
});
}
function showCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#x2').val(c.x2);
$('#y2').val(c.y2);
$('#destWidth').val(c.w);
$('#destHeight').val(c.h);
};
function clearCoords()
{
$('#coords input').val('');
};
--------------------------------------------------------------------后台处理----------------------------------------------------------------------------------------------
后台的全部传上来吧
/**
*
*/
package com.cqzb.mall.web.controller;
import java.io.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.awt.Graphics;
import java.awt.color.ColorSpace;
import javax.imageio.ImageIO;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.cqzb.admin.annotation.MenuO;
import com.cqzb.admin.entity.Attachment;
import com.cqzb.admin.entity.Login;
import com.cqzb.admin.service.AttachmentService;
import com.cqzb.admin.vo.AttachmentVo;
import com.cqzb.frame.dto.resources.Constant;
import com.cqzb.frame.helper.FileHelper;
import com.cqzb.frame.helper.StringTool;
import com.cqzb.frame.hibernate.criteria.Pager;
import com.cqzb.frame.web.controller.CommonController;
/**
* 文件上传控件
* @author 贺亮
*
*/
@Controller
public class AttachmentController extends CommonController {
@Autowired
private AttachmentService attachmentService;
/**
* 跳转到后台上传文件管理
* @return
*/
@RequestMapping("admin/attachment/uploadManager")
@MenuO(name="上传文件管理",code="attachment-manager",parent="system-manager",type = Constant.LINK)
public String uploadManager() {
return "admin/system/attachment_manager";
}
/**
* 获得所有上传的文件信息
* @return
*/
@RequestMapping("admin/attachment/findAllAttachment")
@ResponseBody
@MenuO(name="所有文件信息",code="attachment-findAll",parent="attachment-manager",type =
Constant.AFFILIATED)
public List<Attachment> findAll() {
return attachmentService.findAll();
}
/** <系统上传文件管理>页面---列表请求 */
@RequestMapping("admin/attachment/manager/page")
@ResponseBody
@MenuO(name="系统上传文件页",code="attachment-manager-page",parent="attachment-manager",type =
Constant.AFFILIATED)
public Map<String,Object> page(AttachmentVo vo){
Pager<Attachment> pager = attachmentService.getAttachmentPage(vo);
/*开始对象转换*/
List<AttachmentVo> list = new ArrayList<AttachmentVo>();
for(Attachment attachment:pager.getRows()){
list.add(new AttachmentVo(attachment));
}
/*开始配置页面传值*/
Map<String,Object> map = new HashMap<String,Object>();
map.put("rows", list);
map.put("total", pager.getTotal());
return map;
}
@RequestMapping("portal/attachment/uploadFile")
@ResponseBody
@MenuO(name="上传文件",code="attachment-uploadFile",parent="attachment-manager",type =
Constant.AFFILIATED)
public Map<String, Object> uploadFile(HttpServletRequest request,HttpServletResponse response)
throws Exception {
Map<String, Object> map = new HashMap<String,Object>();
AttachmentVo vo = new AttachmentVo();
//取得上传的文件
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("uploadFileName");
// response.setContentType("text/html");
// response.setCharacterEncoding("UTF-8");
//得到文件名称
String realFileName = file.getOriginalFilename();
String suffix = realFileName.substring(realFileName.indexOf("."), realFileName.length());
//判断文件类型是否可用和文件类型
Map<String, Object> attMap = StringTool.attachmentType(suffix);
if(!(Boolean) attMap.get("flag")) {
map.put("result", "typeError");
Fail(map);
return map;
}
String fileRealPath = request.getSession().getServletContext().getRealPath("/")+"upload\\";
String webPath = "upload/";
String randomName = FileHelper.getRandomFileName(suffix);
//判断文件夹是否存在
File targerFile = new File(fileRealPath);
//判断是否存在目录
if(!targerFile.exists()) {
targerFile.mkdirs();
}
//保存文件
File uploadFile = new File(fileRealPath+randomName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
//配置文件实体信息
vo.setaTypeId(Long.valueOf(attMap.get("type").toString()));//文件类型
vo.setaPath(webPath+randomName);//路径
vo.setaName(randomName);//文件名
Login login = (Login)request.getSession().getAttribute(Constant.LOGIN_SESSION);
vo.setUploadUser(login.getId());
Attachment result = attachmentService.addOrUpdate(vo);
//返回上传信息
map.put("result", new AttachmentVo(result));
Success(map);
return map;
}
/**
* 图像切割(改) *
* @param srcImageFile 源图像地址
* @param dirImageFile 新图像地址
* @param x 目标切片起点x坐标
* @param y 目标切片起点y坐标
* @param destWidth 目标切片宽度
* @param destHeight 目标切片高度
*/
@RequestMapping("portal/attachment/imageCut")
@ResponseBody
@MenuO(name="上传文件处理",code="attachment-imageCut",parent="attachment-manager",type =
Constant.AFFILIATED)
public Map<String, Object> abscut(String srcImageFile, int x, int y, int destWidth,int
destHeight,HttpServletRequest request) {
Map<String, Object> map = new HashMap<String,Object>();
AttachmentVo vo = new AttachmentVo();
Image img;
ImageFilter cropFilter;
//获得源文件文件名
String extracted = srcImageFile.substring(srcImageFile.lastIndexOf("/") + 1);
//剪切后存储路径
String dirImageFile=request.getSession().getServletContext().getRealPath("/")+"upload/cut/";
//判断文件夹是否存在
File targerFile = new File(dirImageFile);
//判断是否存在目录
if(!targerFile.exists()) {
targerFile.mkdirs();
}
dirImageFile+=extracted;
try {
// 读取源图像
srcImageFile=request.getSession().getServletContext().getRealPath("/")+srcImageFile;
BufferedImage bi = ImageIO.read(new File(srcImageFile));
int srcWidth = bi.getWidth(); // 源图宽度
int srcHeight = bi.getHeight(); // 源图高度
if (srcWidth >= destWidth && srcHeight >= destHeight) {
Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
// 改进的想法:是否可用多线程加快切割速度
// 四个参数分别为图像起点坐标和宽高
// 即: CropImageFilter(int x,int y,int width,int height)
cropFilter = new CropImageFilter(x, y, destWidth, destHeight);
img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(),
cropFilter));
BufferedImage tag = new BufferedImage(destWidth, destHeight,BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // 绘制缩小后的图
g.dispose();
// 输出为文件
ImageIO.write(tag, "JPEG", new File(dirImageFile));
//配置文件实体信息
vo.setaTypeId(Long.valueOf(1));//文件类型
vo.setaPath("upload/cut/"+extracted);//路径
vo.setaName(extracted);//文件名
Login login = (Login)request.getSession().getAttribute(Constant.LOGIN_SESSION);
vo.setUploadUser(login.getId());
Attachment result = attachmentService.addOrUpdate(vo);
//返回上传信息
map.put("result", new AttachmentVo(result));
Success(map);
return map;
}
} catch (Exception e) {
e.printStackTrace();
}
map.put("result", "保存错误");
Fail(map);
return map;
}
}
2014-9-26记录