图片转Base64

1.依赖

需要用到的类:org.apache.commons.codec.binary.Base64,依赖如下:

        <dependency>
            <scope>compile</scope>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>20041127.091804</version>
        </dependency>

2.实现

    //可能用到的前缀
    public static final String BASE64_PREFIX = "data:image/jpeg;base64,";

    public static String img2Base64(String imgRealPath){
        try (InputStream is = new FileInputStream(new File(imgRealPath))) {
            //字节数组
            byte[] data = new byte[is.available()];
            //填充数组
            is.read(data);
            //改变为base64式的字节数组
            data = Base64.encodeBase64(data);
            return new String(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

测试输出结果:

/9j/4AAQSkZJ...此处省略中间的Base64编码值...V/LI//2Q==
posted @ 2020-08-25 23:03  youngyajun  阅读(286)  评论(0编辑  收藏  举报