一. 自己实现byte数组拷贝
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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(); } } } |