/**
* 将图片转为base64
* @param filePath
* @return
*/
public static String encodeImage(String filePath) {
BufferedInputStream in = null;
byte[] data = null;
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
in = new BufferedInputStream(new FileInputStream(filePath));
byte[] buf = new byte[1024];
int len = -1;
while ((len = in.read(buf)) != len) {
baos.write(buf, 0, len);
}
in.close();
baos.close();
data = baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("文件读取失败", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error("关闭资源流异常", e);
in = null;
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
log.error("关闭资源流异常", e);
baos = null;
}
}
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
/**
* 将base64转为图片
* @param imagebase64
* @param filePath
* @return
*/
public static String decodeImage(String imagebase64, String filePath) {
BufferedOutputStream os = null;
byte[] data = null;
try {
os = new BufferedOutputStream(new FileOutputStream(filePath));
data = Base64.decodeBase64(imagebase64);
os.write(data);
os.flush();
os.close();
return filePath;
} catch (IOException e) {
throw new RuntimeException("图片解码失败", e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error("关闭资源异常", e);
os = null;
}
}
}
}
/**
Base64转为图片流
*/
public static byte[] getImgByte(String base64Str) {
if (base64Str == null) {
return null;
}
try {
return Base64.decodeBase64(base64Str);
} catch (IOException e) {
log.error("解析base64图片异常", e);
return null;
}
}
/**
* 图片流装为base64
* @param fileByte
* @return
*/
public static String getImgStrByByte(byte[] fileByte) {
// 对字节数组进行Base64编码,得到Base64编码的字符串
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(fileByte);
}
01-07
8464

11-07
1050
