Im4Java的安裝文檔見:http://blog.csdn.net/tangpengtao/article/details/9208047css
JCrop的插件:jquery.Jcrop.jshtml
jQuery之Jcropjava
IM4Java的jar:im4java-1.2.0.jarjquery
jcrop的調用js以下:linux
/**
* 上傳頭像成功後保存
* @param file
*/
uploadMyPicSuccess: function(file, data){
var filePath = data.path; // 附件地址
var width = data.width; // 原圖寬度
var height = data.height; // 原圖高度
var containWidth = 445;
var containHeight = 314;
var marginLeft = (containWidth - width) / 2;
var marginTop = (containHeight - height) / 2;
//截取區域的圖片
$("#img_1").css({width:width, height:height, "margin-left":marginLeft, "margin-top":marginTop})
.attr("src", fileURL+'/'+data.path);
//50*50規格
$("#img_3").attr("src", fileURL+'/'+data.path);
//120*120規格
$("#img_2").attr("src", fileURL+'/'+data.path);
if(jcrop) jcrop.destroy();
var jcrop = $.Jcrop("#img_1", {
aspectRatio: 1,
onChange: showPreview,
//showPreview爲裁剪圖片的function,後面寫
onSelect: showPreview,
setSelect: [ 0, 0, 100, 100]
});
$(".jcrop-holder").css({"margin-left":marginLeft, "top":marginTop});
//建立隱藏域,保存頭像真實存儲路徑
$("#newUrl").val(filePath);
//點擊預覽按鈕
$("#previewBtn").show().click(function(){
cropPic();
});
// 獲取裁剪後的圖片,預覽
function cropPic(){
var mypic =$("#newUrl").val();
$.ajax({
async: false,
type: "POST",
dataType:"json",
cache: false,
url: baseURL +"/userinfo/cropPic",//裁剪圖片的action
data: "imageX=" +cropImage.x + "&imageY=" + cropImage.y + "&imageWidth=" + cropImage.w + "&imageHeight=" + cropImage.h + "&fileUrl=" + encodeURIComponent(mypic),
success: function(data){
if(data.success){
var smallPicUrl = data.path.split(",")[0];
var normalPicUrl = data.path.split(",")[1];
// 建立隱藏域,保存小圖
$("#smallUrl").val(smallPicUrl);
$("#img_3").attr("src", fileURL+"/" + smallPicUrl);
$("#img_2").attr("src", fileURL+"/" + normalPicUrl);
// 激活保存按鈕
$("#saveBtn").show();
}
},
error:function(data){
alert("更新失敗,請從新上傳 ");
}
});
}
},
定義裁剪預覽:ajax
//圖片裁剪預覽 window.cropImage = {}; //選中裁剪內容後,獲取裁剪座標 function showPreview(coords){ cropImage.x = coords.x; cropImage.y = coords.y; cropImage.w = coords.w==0?1:coords.w; cropImage.h = coords.h==0?1:coords.h; }
圖片處理:json
1.圖片上傳後,假設顯示圖片的區域爲413*350,則,上傳後,把圖片按原有的尺寸,等比裁減windows
/** * 上傳我的頭像 * @param request * @param response * @param file 上傳的圖片 * @param width 界面裁剪控件的寬度 * @param height 界面裁剪控件的高度 * @throws IOException */ @RequestMapping(value = "/uploadHeadPic") public void uploadHeadPic(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file, @RequestParam(value="width",defaultValue="445")int width, @RequestParam(value="height",defaultValue="314") int height) throws IOException { if (logger.isDebugEnabled()) { logger.debug("頭像上傳開始"); } // 響應JSON Map<String, Object> result = new HashMap<String, Object>(); boolean success = false; String fileName = file.getOriginalFilename(); // 生成一個臨時文件名 fileName = "tmp_" + GenUUIDHelper.genFileName(fileName); if (FileUtils.isPicture(fileName)) { Map<String, Object> r = fileManage.resizePicture(file.getInputStream(),fileName,request.getSession().getServletContext().getRealPath("/"), width, height); String url = (String) r.get("path"); if (url != null) { result.put("path", url.replace("\\", "/")); result.put("width", r.get("width")); result.put("height", r.get("height")); success = true; } else { success = false; } } result.put("success", success); if (logger.isDebugEnabled()) { logger.debug("swf上傳結束"); } // 輸出響應,文件上傳不支持ajax方式的響應contentType,因此不能使用ResponseBody response.setCharacterEncoding(HttpUtil.ENCODING_UTF8); ObjectMapper objectMapper = new ObjectMapper(); try { JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8); objectMapper.writeValue(jsonGenerator, result); response.getOutputStream().flush(); } catch (IOException e) { logger.error("writeResponse", e); } }
2.點擊預覽後,按尺寸 120*120 和 50*50裁減2張圖片,並返回圖片路徑,作爲預覽圖片app
/** * 裁剪我的頭像; * @param request * @param response * @param x * @param y * @param width * @param height * @param fileUrl * @throws Exception */ @RequestMapping(value = "/cropPic") public void cropPic(HttpServletRequest request, HttpServletResponse response, @RequestParam("imageX") Double x, @RequestParam("imageY") Double y, @RequestParam("imageWidth") Double width, @RequestParam("imageHeight") Double height, @RequestParam("fileUrl") String fileUrl) throws Exception{ if (logger.isDebugEnabled()) { logger.debug("裁剪我的頭像開始"); } String contentPath=request.getSession().getServletContext().getRealPath("/"); fileUrl = contentPath + File.separator + fileUrl; if (logger.isDebugEnabled()) { logger.debug("fileUrl="+fileUrl); } Map<String, Object> resultMap = new HashMap<String, Object>(); File imgFile = new File(fileUrl); if (imgFile.exists()) { if (logger.isDebugEnabled()) { logger.debug("imgFile.exists..........."); } // 壓縮並保存文件 String[] fileKey = fileManage.cropPicture(fileUrl, contentPath,x.intValue(), y.intValue(), width.intValue(), height.intValue()); resultMap.put("success", true); resultMap.put("path", fileKey[0].replace("\\", "/") + "," + fileKey[1].replace("\\", "/")); }else{ resultMap.put("success", false); } if (logger.isDebugEnabled()) { logger.debug("swf裁剪我的頭像結束"); } // 輸出響應,文件上傳不支持ajax方式的響應contentType,因此不能使用ResponseBody response.setCharacterEncoding(HttpUtil.ENCODING_UTF8); ObjectMapper objectMapper = new ObjectMapper(); try { JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8); objectMapper.writeValue(jsonGenerator, resultMap); response.getOutputStream().flush(); } catch (IOException e) { logger.error("writeResponse", e); } }
3.共用的圖片處理類:async
@Component() public class Im4JavaPictureHandle implements IPictureHandle { private static Log logger = LogFactory.getLog(Im4JavaPictureHandle.class); @Override public void cropImage(String srcPath, String newPath, int x, int y, int width, int height, int saveWidth, int saveHeight) throws Exception { IMOperation op = new IMOperation(); op.addImage(srcPath); /** * width:裁剪的寬度 * height:裁剪的高度 * x:裁剪的橫座標 * y:裁剪的挫座標 */ op.crop(width, height, x, y); op.resize(saveWidth, saveHeight); op.addImage(newPath); ConvertCmd convert = new ConvertCmd(true); //linux下不要設置此值,否則會報錯 if(!System.getProperty("os.name").equals("Linux")&&!StringUtils.isNullOrEmpty(FileConsts.GRAPHICS_MAGICK_PATH)) { convert.setSearchPath(FileConsts.GRAPHICS_MAGICK_PATH); } convert.run(op); } @Override public int[] resizeImage(String srcPath, String newPath, int width, int height) throws Exception { int[] target = scaleWidthAndHight(srcPath,width,height); width = target[0]; height = target[1]; IMOperation op = new IMOperation(); op.addImage(srcPath); op.resize(width, height); op.addImage(newPath); ConvertCmd convert = new ConvertCmd(true); //linux下不要設置此值,否則會報錯 if(!System.getProperty("os.name").equals("Linux")&&!StringUtils.isNullOrEmpty(FileConsts.GRAPHICS_MAGICK_PATH)) { convert.setSearchPath(FileConsts.GRAPHICS_MAGICK_PATH); } convert.run(op); return target; } public int[] scaleWidthAndHight(String srcPath,int w,int h) throws IOException{ Image srcImage = null; int[] target = new int[2]; FileInputStream oldIs = new FileInputStream(srcPath); srcImage = javax.imageio.ImageIO.read(oldIs); //獲得圖片原始大小,以便按比例壓縮 int width = srcImage.getWidth(null); int height = srcImage.getHeight(null); // 特殊處理 當w和h均爲0時,長,寬默認爲圖片原大小 if(w==0 && h==0){ w = width; h = height; }else if(h==0){ if(width>=w){ h = (int)Math.round((height * w * 1.0 / width)); }else{ w = width; h = height; } } else{ if ( width >= height){ if(width >= w){ h = (int)Math.round((height * w * 1.0 / width)); }else{ w = width; h = height; } }else{ if(height >= h ){ w = (int)Math.round((width * h * 1.0 / height)); }else{ w = width; h = height; } } } target[0] = w; target[1] = h; oldIs.close(); return target; } }
在linux和windows下的安裝分別以下:
http://www.cnblogs.com/jennybackup/p/3951935.html