最近在倒弄個一個網站,www.thinkdee.com 沒有完成,還在做,這里要用到用戶頭像設置,本來想自己處理的,看到網上美圖功能太強大了,就試了一把!
美圖開放平台:http://open.web.meitu.com/
開發文檔:http://open.web.meitu.com/wiki/
頭像設置示例:http://open.web.meitu.com/products/#M4
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>美圖WEB開放平台</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://open.web.meitu.com/sources/xiuxiu.js" type="text/javascript"></script> <script type="text/javascript"> window.onload=function(){ xiuxiu.embedSWF("altContent",5,"100%","100%"); /*第1個參數是加載編輯器div容器,第2個參數是編輯器類型,第3個參數是div容器寬,第4個參數是div容器高*/ xiuxiu.setUploadType(2); xiuxiu.setUploadURL("${webRoot}/user/uploadface");//修改為您自己的上傳接收圖片程序 xiuxiu.onBeforeUpload = function(data, id){ xiuxiu.setUploadArgs({filetype: data.type, type: "image", filename: data.name }); } xiuxiu.onInit = function () { xiuxiu.loadPhoto("http://open.web.meitu.com/sources/images/1.jpg"); } xiuxiu.onUploadResponse = function(data) { if(data){ alert("頭像設置成功"); location.href="${webRoot}/user/showuserinfo"; }else{ alert("頭像設置失敗"); } } } </script> <style type="text/css"> html, body { height:100%; overflow:hidden; } body { margin:0; } </style> </head> <body> <div id="altContent"> <h1>美圖秀秀</h1> </div> </body> </html>
后台圖片處理:
@RequestMapping("uploadface") @ResponseBody public boolean uploadface(HttpServletRequest request,HttpServletResponse response,@RequestParam("Filedata") MultipartFile file ) throws Exception{ if(!file.isEmpty()){ //得原始名字1.jpg String originName = file.getOriginalFilename(); //取出.jpg String fileType = originName.substring(originName.indexOf(".")); //生成新文件名 abc String newFileName = UUIDGenerator.getUUID(); //生成abc.jpg String newFile = newFileName + fileType; //文件生成的路徑-文件夾 // String uploadDir = MyWebUtil.getUploadHeadPath(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String datePath = sdf.format(new Date()); String rootPath = MyWebUtil.getWebRootPath(); String imgPath = "/upload/head/"+ datePath+"/"; String uploadDir = rootPath + imgPath ; File f = new File(uploadDir); if(!f.exists()){ f.mkdirs(); } String toDiskPath = imgPath + newFile; //生成的文件路徑 String filePath = uploadDir + newFile; byte[] bytes = file.getBytes(); FileOutputStream fos = new FileOutputStream(filePath); fos.write(bytes); //寫入文件 //更新數據庫 Subject subject = SecurityUtils.getSubject(); String logName = (String)subject.getPrincipal(); if(StringUtils.isNotBlank(logName)){ User u = userService.getByUserName(logName); u.setUface(toDiskPath); userService.updateUser(u); } //生成小圖,中圖頭像 String mid = filePath +"-mid" +fileType; String sml = filePath +"-sml" +fileType; ScaleImage is = new ScaleImage(); is.saveImageAsJpg(filePath, sml, 30, 30); is.saveImageAsJpg(filePath, mid, 60, 60); return true; } return false; }