图片转base64

1.使用

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.13</version>
</dependency>

2.编码:

    public static String encodeBase64File(String path){
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(path);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(5000);
            int responseCode = con.getResponseCode();
            log.info("responseCode:" + responseCode + "-------------- 图片url:" + con.getURL());
            if (responseCode > 300 || responseCode < 200) {
                String[] s = path.split("/");
                if (s.length - 1 >= 0) {
                    String newUrl = "https://qimg.0easy.com/".concat(s[s.length - 1]);
                    con.disconnect();
                    url = new URL(newUrl);
                    con = (HttpURLConnection) url.openConnection();
                    con.setConnectTimeout(5000);
                    con.setReadTimeout(30000);
                    con.connect();
                    responseCode = con.getResponseCode();
                }
                log.info("responseCode:" + responseCode + "-------------- 图片url:" + con.getURL());
                if (responseCode > 300 || responseCode < 200) {
                    con.disconnect();
                    return "图片信息获取失败";
                }
            }

            InputStream is = con.getInputStream();
            // 将内容放到内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
//        String header="data:image/jpg;base64,";//如果是在html中则加上
        return Base64.encodeBase64String(data.toByteArray());
    }

解码:

public static void toFile(String base64Code, String targetPath) throws Exception {
    byte[] buffer = Base64.decodeBase64(base64Code);
    FileOutputStream out = new FileOutputStream(targetPath);
    out.write(buffer);
    out.close();
}

同样的转pdf

byte[] bytes = FileUtils.readFileToByteArray(new File("c:\\z_test\\test1.pdf"));
String s = Base64.encodeBase64String(bytes);
System.out.println(s);
byte[] buffer = Base64.decodeBase64(s);
FileOutputStream out = new FileOutputStream("C:\\z_test\\2.pdf");
out.write(buffer);
out.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值