在項目中,我們會經常遇到圖片的一些處理,比如說保存圖片,下載圖片,而我遇到的需求經常的做法是將圖片經過base64加密後存入數據庫,前端需要的時候,就將加密後的字符串傳遞給前端,前端自行解密即可。
以下代碼就是常規的加密解密代碼:
public class Base64Utils {
/**
* 圖片轉化成base64字符串
*
* @param imgPath 圖片路徑
* @return 返回加密後的字符串
*/
// 將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理
public static String GetImageStr(String imgPath) {
// 待處理的圖片
String imgFile = imgPath;
InputStream in = null;
byte[] data = null;
// 返回Base64編碼過的字節數組字符串
String encode = null;
// 對字節數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
try {
// 讀取圖片字節數組
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return encode;
}
/**
* base64字符串轉化成圖片
*
* @param imgData 圖片編碼
* @param imgFilePath 存放到本地路徑
* @return
* @throws IOException
*/
@SuppressWarnings("finally")
// 對字節數組字符串進行Base64解碼並生成圖
public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException {
// 圖像數據爲空
if (imgData == null){
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
OutputStream out = null;
try {
out = new FileOutputStream(imgFilePath);
// Base64解碼
byte[] b = decoder.decodeBuffer(imgData);
for (int i = 0; i < b.length; ++i) {
// 調整異常數據
if (b[i] < 0) {
b[i] += 256;
}
}
out.write(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.flush();
out.close();
return true;
}
}
}