@Test
public void imageToBase64(){
byte[] data = null;
FileInputStream in = null;
PrintWriter printWriter = null;
try {
in = new FileInputStream("D:\\image.jpg");
FileOutputStream fileOutputStream = new FileOutputStream("D:\\11.txt");
printWriter = new PrintWriter(fileOutputStream);
data = new byte[in.available()];
in.read(data);//关键要点
String str1 = Base64.encodeBase64String(data);//tomcat包
java.util.Base64.Encoder encoder2 = java.util.Base64.getEncoder();
String str2 = encoder2.encodeToString(data);
String str3 = cn.hutool.core.codec.Base64.encode(new File("D:\\image.jpg"));
System.out.println(str3);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
in.close();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
图片转base64编码很多工具包都有,java.util,hutool,tomcat,随意选择一个即可
public static void base64ToImage(String base64str) {
String imgPath = "D:\\image.jpg";
FileOutputStream out = null;
try {
out = new FileOutputStream(imgPath);
java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
byte[] imageData = decoder.decode(base64str);
out.write(imageData);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文:https://www.cnblogs.com/xzh-hash/p/14623830.html