Java实现图片转base64,base64转图片
1、图片转base64
package com.xxx.xxx.xxx;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Base64;
public class TestPicToBase64 {
public static void main(String[] args) {
String filePath = "D:\\xx\\xxx\\aaaaaa.png";
String base64String = imageToBase64(filePath);
System.out.println("Base64 string: \n" + base64String);
String writeFileName = System.currentTimeMillis() + "";
String writeFilePath = "D:\\xxx\\xxx\\图片base64\\" + writeFileName + ".txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(writeFilePath))) {
writer.write(base64String);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String imageToBase64(String imagePath) {
try {
FileInputStream imageInputStream = new FileInputStream(imagePath);
byte[] imageBytes = new byte[imageInputStream.available()];
imageInputStream.read(imageBytes);
imageInputStream.close();
return Base64.getEncoder().encodeToString(imageBytes);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
2、base64转图片
package com.xxx.xxx.xxx;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.stream.Stream;
public class TestBase64ToPic {
public static void main(String[] args) throws IOException {
String fileName = "D:\\xxx\\xxx\\图片base64\\1724309528845.txt";
Stream<String> lines = Files.lines(Paths.get(fileName));
StringBuffer stringBuffer = new StringBuffer();
lines.forEach(t -> {
stringBuffer.append(t);
});
String filePath = saveImgToLocal(2024000001L, stringBuffer.toString());
System.out.println("文件路径:" + filePath);
}
public static String saveImgToLocal(Long prefix, String imgContent) throws IOException {
String savePath = "D:\\xxx\\xxx\\base64转图片\\";
String fileName = prefix + "_" + DateUtil.nowDate().getTime() + ".jpg";
String filePath = savePath + fileName;
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(filePath));
Base64.Decoder decoder = Base64.getMimeDecoder();
byte[] bt = decoder.decode(imgContent);
os.write(bt);
os.flush();
os.close();
return filePath;
}
}