一. 自己实现byte数组拷贝
public class Base64Util {
private byte[] baseByte= new byte[0];
public static void main(String[] args) {
Base64Util base64Util = new Base64Util();
base64Util.base64Encoding();
}
private void base64Encoding(){
try {
ClassPathResource classPathResource = new ClassPathResource("/images/e88b27550495d06a041a7854fcd07b8c.jpg");
String pre = "data:image/jpg;base64,";
FileInputStream fileInputStream = new FileInputStream(classPathResource.getFile());
int len = 0;
int capacity = 0;
byte [] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1){
baseByte= Arrays.copyOf(baseByte, len + capacity);
System.arraycopy(bytes, 0, baseByte, capacity, len);
capacity += len;
}
Base64.Encoder encoder = Base64.getEncoder();
String encodeToString = encoder.encodeToString(baseByte);
System.out.println("======>>>>>>:" + pre + encodeToString);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二. 使用ByteArrayOutputStream
public class Base64Util {
public static void main(String[] args) {
Base64Util base64Util = new Base64Util();
base64Util.base64Encoding();
}
private void base64Encoding(){
try {
ClassPathResource classPathResource = new ClassPathResource("/images/e88b27550495d06a041a7854fcd07b8c.jpg");
String pre = "data:image/jpg;base64,";
FileInputStream fileInputStream = new FileInputStream(classPathResource.getFile());
int len = 0;
byte [] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1){
data.write(bytes, 0, len);
}
byte[] baseByte = data.toByteArray();
Base64.Encoder encoder = Base64.getEncoder();
String encodeToString = encoder.encodeToString(baseByte);
System.out.println("======>>>>>>:" + pre + encodeToString);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}