一. 自己实现byte数组拷贝
public class Base64Util {// base64图片 存储的byte数组 private byte[] baseByte= new byte[0]; public static void main(String[] args) { Base64Util base64Util = new Base64Util(); base64Util.base64Encoding(); } private void base64Encoding(){ try { // 从本地resource目录下获取图片 ClassPathResource classPathResource = new ClassPathResource("/images/e88b27550495d06a041a7854fcd07b8c.jpg"); // base64图片前缀 String pre = "data:image/jpg;base64,"; // 读取图片 FileInputStream fileInputStream = new FileInputStream(classPathResource.getFile()); // 读取字节长度 int len = 0; // baseByte数组的容量 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编码器 Base64.Encoder encoder = Base64.getEncoder(); // 将字节数组转换base64 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 { // 从本地resource目录下获取图片 ClassPathResource classPathResource = new ClassPathResource("/images/e88b27550495d06a041a7854fcd07b8c.jpg"); // base64图片前缀 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编码器 Base64.Encoder encoder = Base64.getEncoder(); // 将字节数组转换base64 String encodeToString = encoder.encodeToString(baseByte); System.out.println("======>>>>>>:" + pre + encodeToString); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } }}
来源地址:https://blog.csdn.net/m0_47724597/article/details/131913350