java图片转base64和base64保存到本地
/**
* 本地图片转换Base64的方法
*
* @param imgPath
*/
private static String ImageToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(Objects.requireNonNull(data));
}
public static boolean GenerateImage(String imgStr, String photoname) {
//对字节数组字符串进行Base64解码并生成图片
//图像数据为空
if (imgStr == null)
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) {
//调整异常数据
b[i] += 256;
}
}
//生成jpeg图片
String imagePath = ResourceUtils.getURL("classpath:").getPath();
//System.currentTimeMillis()
//新生成的图片
String imgFilePath = imagePath + photoname;
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}