private static void doConvImgToBase(File file) {
/*当前是文件夹吗?*/
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File item : files) {
doConvImgToBase(item);
}
}else {
try {
// byte[] bytes = FileUtils.readFileToByteArray(file);
// String base64 = "data:image/png;base64,"+new String(Base64.getEncoder().encode(bytes), StandardCharsets.UTF_8);
String base64 = "data:image/png;base64,"+imageToBase64Str(file);
File targetFile = new File(file.getParent() +File.separatorChar+ StrUtil.subBefore(file.getName(),".",true) + ".txt");
FileUtil.writeString(base64,targetFile,StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* 图片转base64字符串
*
* @param imgFile 图片路径
* @return
*/
public static String imageToBase64Str(File 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);
}
java 图片转base64 png格式文件
最新推荐文章于 2024-07-22 14:15:06 发布