admin
2021-05-14 ae2294be876ac4595d7b31b36c0057726d12354f
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.yeshi.fanli.util;
 
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
public class ImageToBase64 {
 
    public static void main(String[] args) {
        // 第一个:把网络图片装换成Base64
//        String netImagePath = "http://ec-1255749512.file.myqcloud.com/swiperPic/c7847b574a79400298bc63706fd89faf.jpeg";
        
        String netImagePath = "http://ec-1255749512.file.myqcloud.com/editor/img/evaluate/df21d25edd924837b6f8b1f8eaeeac97.jpeg";
        // 下面是网络图片转换Base64的方法
        String netImageToBase64 = NetImageToBase64(netImagePath);
 
//        System.out.println(netImageToBase64);
        // 下面是本地图片转换Base64的方法
         //String imagePath = "本地图片路径";
        // ImageToBase64(imagePath);
    }
 
    /**
     * 网络图片转换Base64的方法
     *
     * @param netImagePath     
     */
    public static String NetImageToBase64(String netImagePath) {
        try {
            // 创建URL
            URL url = new URL(netImagePath);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
 
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(data.toByteArray());
            // 关闭流
            is.close();
            return encode;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 本地图片转换Base64的方法
     *
     * @param imgPath     
     */
    public static String ImageToBase64(String imgPath) {
        try {
            InputStream in = new FileInputStream(imgPath);
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
            
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}