如何使用Java將圖片轉出base64,將base64轉出圖片
如下需求
圖片轉成base64
//圖片轉base64
public static String getImageStr(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
base64轉成圖片
//base64 轉成圖片
public static boolean generateImage(String imgStr, String imgFilePath) {// 對字節數組字符串進行Base64解碼並生成圖片
if (imgStr == null) // 圖像數據爲空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解碼
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 調整異常數據
bytes[i] += 256;
}
}
// 生成jpg圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}