【http图片地址转base64】

工作中有这样一个需求,在推送给用户的信息中,图片要以base64方式推送,已知图片已上传到minio服务器,图片可根据http地址进行访问…

直接上代码,开干

            byte[] buffer = null;
            InputStream inputStream = null;
            String picurl = "http://xxxxxxxx";
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();){
                // 创建URL
                URL picurl = new URL(picurl );
                // 创建链接
                HttpURLConnection conn = (HttpURLConnection) picurl.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                inputStream = conn.getInputStream();
                // 将内容读取内存中
                buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                buffer = outputStream.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        // 关闭inputStream流
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 对字节数组进行Base64编码
            Base64.Encoder encode = Base64.getEncoder();
            String code = encode.encodeToString(buffer);

通过上诉代码即可完成http地址转base64 的操作,亲测有用.

读者需要注意,图片转base64时,文件太大,转成的base64后长度非常大,应尽量避免转base64操作.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值