Java+Jcrop實現圖片裁剪並儲存到伺服器
阿新 • • 發佈:2018-12-14
-
外掛下載
-
前端程式碼
前端程式碼較長,已放至碼雲
示例demo使用的是限制長寬比的圖片選擇方式,其它方式可以訪問官網下載官方壓縮包,裡面有幾個示例demo。
-
後端程式碼
使用的解碼方式是java8下decoder物件,java8以下請選擇其它解碼方式
@RequestMapping(value = "saveImg", method = RequestMethod.POST) public string saveImg(@RequestParam("imageSrc") String imageSrc) { BufferedOutputStream bos = null; try { // base64解碼物件,使用util包下的 final Base64.Decoder decoder = Base64.getDecoder(); // 儲存圖片到本地目錄 String newFildId = UUID.randomUUID().toString() + ".png"; File file = new File("D:/imgServer/" + newFildId); file.createNewFile(); bos = new BufferedOutputStream(new FileOutputStream(file)); // 去掉頭部資訊並儲存到圖片檔案中 bos.write(decoder.decode(imageSrc.replace("data:image/png;base64,", ""))); } catch (IOException e) { e.printStackTrace(); log.error(e.getMessage()); return "false"; } finally { try { bos.close(); } catch (IOException e) { e.printStackTrace(); return "false"; } } return "success"; }
-
頁面載入
儲存之後,頁面使用img標籤讀取(【file:///圖片路徑】的形式可能無效,使用圖片伺服器的形式讀取),步驟如下:
- 在tomcat的server.xml中加入以下語句(路徑自行修改),建立圖片伺服器
<Context docBase="D:/imgServer" path="/imgServer" reloadable="true" />
(如果使用eclipse,需要在eclipse的server中修改,否則重啟eclipse會覆蓋掉)
2.頁面訪問圖片伺服器
<img src="/imgServer/0.png">
-
一些廢話( ̄▽ ̄)~*
圖片的base64編碼可以不解碼(也不要將頭部資訊去掉)直接儲存到資料庫中,頁面展示時將base64編碼直接賦值給img的src屬性應該也可以(未嘗試)。