直接上代碼好不好
方法名:
GenerateImage
傳參:
base64Img:上傳的base64碼
realPath:生成的圖片路徑
imgTypes :圖片類型
String imgBase64 = request.getParameter("userImgbase64");
// 獲取當前服務器路徑
String realPath = request.getServletContext().getRealPath("")+"\\img";
System.out.println(realPath ); // http://192.168.191.1:8080/MyWeb/img
String[] imgType = imgBase64.split(",");
// 獲取圖片類型(如果沒有類型,貌似會報錯)
String imgTypes = imgType[0].toString().substring(11, imgType[0].toString().length()-7);
String userImgbase64 = GenerateImage(imgBase64,realPath,imgTypes);
System.out.println(realPath ); // http://192.168.191.1:8080/MyWeb/img/1532493648717.png
//對字節數組字符串進行Base64解碼並生成圖片 public static String GenerateImage(String base64Img,String realPath,String imgTypes ){ String ret_fileName = null; // 臨時文件路徑 File file_normer = new File(realPath+"/"); if (!file_normer.exists()) { file_normer.mkdirs(); } if (base64Img == null) // 圖像數據為空 return "圖像數據為空"; base64Img = base64Img.replaceAll("data:image/"+imgTypes+";base64,", ""); BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解碼 byte[] b = decoder.decodeBuffer(base64Img); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 調整異常數據 b[i] += 256; } } // 生成jpeg圖片 ret_fileName = System.currentTimeMillis()+"."+imgTypes+""; File file = new File(realPath + "/" + ret_fileName ); OutputStream out = new FileOutputStream(file); out.write(b); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return ret_fileName ; }