- 問題:客戶端是android,通過json傳輸圖片到服務端,服務端解析出來,生成圖片時損壞。
- 在客戶端將圖片轉為string格式,這里要注意的是通過Base64.encode進行編碼,再通過jackson序列化
1 /** 2 * 利用BASE64Encoder對圖片進行base64轉碼將圖片轉為string 3 * 4 * @param imgFile 文件路徑 5 * @return 返回編碼后的string 6 */ 7 public static String f_imageToString(String imgFile) 8 { 9 // 將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理 10 InputStream in = null; 11 byte[] data = null; 12 // 讀取圖片字節數組 13 try 14 { 15 in = new FileInputStream(imgFile); 16 data = new byte[in.available()]; 17 in.read(data); 18 in.close(); 19 } 20 catch (IOException e) 21 { 22 e.printStackTrace(); 23 } 24 // 返回Base64編碼過的字節數組字符串 25 String str = new String(Base64.encode(data)); 26 return str; 27 }
- 在服務端通過jackson取到base64編碼后傳過來的string數據,再進行base64解碼,生成圖片
1 /** 2 * 通過BASE64Decoder解碼,並生成圖片 3 * 4 * @param imgStr 解碼后的string 5 * @return 6 */ 7 public static boolean f_stringToImage(String imgStr, String imgFilePath) 8 { 9 // 對字節數組字符串進行Base64解碼並生成圖片 10 if (imgStr == null) 11 return false; 12 try 13 { 14 // Base64解碼 15 byte[] b = Base64.decode(imgStr); 16 for (int i = 0; i < b.length; ++i) 17 { 18 if (b[i] < 0) 19 { 20 // 調整異常數據 21 b[i] += 256; 22 } 23 } 24 // 生成jpeg圖片 25 OutputStream out = new FileOutputStream(imgFilePath); 26 out.write(b); 27 out.flush(); 28 out.close(); 29 return true; 30 } 31 catch (Exception e) 32 { 33 return false; 34 } 35 }
