Home 图片转BASE64
Post
Cancel

图片转BASE64

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
public static String getImageStr(File file, String fileType) 
            throws IOException {
    String fileContentBase64 = null;
    String base64Str = "data:" + fileType + ";base64,";
    String content = null;
    //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
    InputStream in = null;
    byte[] data = null;
    //读取图片字节数组
    try {
        in = new FileInputStream(file);
        data = new byte[in.available()];
        in.read(data);
        in.close();
        //对字节数组Base64编码
        if (data == null || data.length == 0) {
            return null;
        }
        content = Base64.encodeBytes(data);
        if (content == null || "".equals(content)) {
            return null;
        }
        fileContentBase64 = base64Str + content;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return fileContentBase64;
}

public static void main(String[] args) throws IOException {
    String base64_str = getImageStr(new File("D:\\test.jpg"), "jpg");
}
This post is licensed under CC BY 4.0 by the author.