Base64
import java.io.*;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
public class Base64Util {
/**
* base64字符串转化成图片
*
* @param imgData 图片base64码
* @param imgFilePath 存放到本地路径
* @return
* @throws IOException
*/
public static boolean generateImage(String imgData, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
if (imgData == null) // 图像数据为空
return false;
if (imgData.contains("base64")) {
imgData = imgData.substring(imgData.indexOf(",") + 1);
}
Decoder decoder = Base64.getDecoder();
OutputStream out = null;
try {
out = new FileOutputStream(imgFilePath);
// Base64解码
byte[] b = decoder.decode(imgData);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
out.write(b);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//将字节数组转为base64
public static String encode(byte[] bytes) {
Encoder encoder = Base64.getEncoder();
String answer = "";
// 读取图片字节数组
answer = new String(encoder.encode(bytes));
return answer;
}
//将文件转码为base64
public static String encode(File file) {
try {
byte[] bytes = FileUtil.readFileByBytes(file);
return encode(bytes);
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
//根据文件路径获取文件,并转码为base64
public static String encode(String filePath) {
try {
byte[] bytes = FileUtil.readFileByBytes(filePath);
return encode(bytes);
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
Comments | 0 条评论