將圖片轉(zhuǎn)換為base64位方便存儲秃踩,base64位可以轉(zhuǎn)換為各種類型圖片
將圖片轉(zhuǎn)換為base64位
// 圖片轉(zhuǎn)化成base64字符串
public static String getImageToBase64(String imgFile) {
//imgFile = "C:/Users/Administrator/Desktop/12.png";// 待處理的圖片
InputStream in = null;
byte[] data = null;
// 讀取圖片字節(jié)數(shù)組
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 對字節(jié)數(shù)組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64編碼過的字節(jié)數(shù)組字符串
}
Base64位轉(zhuǎn)換為圖片
// base64字符串轉(zhuǎn)化成圖片
public static boolean base64ToImage(String imgStr) { // 對字節(jié)數(shù)組字符串進行Base64解碼并生成圖片
if (imgStr == null) // 圖像數(shù)據(jù)為空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解碼
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 調(diào)整異常數(shù)據(jù)
b[i] += 256;
}
}
// 生成jpeg圖片
String imgFilePath = "C:/Users/Administrator/Desktop/test.png";// 新生成的圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}