将本地图片或者网络图片转base64字符串

场景说明:

由于种种原因,例如:内网,等...。无法在的程序里直接用图片的链接显示,这是通常是将图片下载下来,在将下载的图片进行base64转码显示

base64转码说明:

  1. 使用java.util.Base64,对字节数组进行Base64编码
  2. 将图片转成base64字符串以后 要加上前缀data:image/png;base64,
  3. 小编封装的工具类采用的是java.net.URL
  4. 文件下载传统的和okhttp下载比较,请看小编这篇博客 ==》文章入口

将本地图片转base64字符串:

01、将文件读取封装成工具类

说明:使用java.util.Base64,对字节数组进行Base64编码

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @author suqinyi
 * @Date 2021/4/23
 */
public class ImgBase64Util {

    /**
     * 将本地图片转成 base64 字符串
     * @param filePath 本地文件的位置
     * @return
     */
    public static String LocalImgToBase64(String filePath) {
        System.out.println("filePath:" + filePath);
        if (filePath == null) {
            return null;
        }
        File file = new File(filePath);
        ByteArrayOutputStream out = null;
        try {
            FileInputStream in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            byte[] b = new byte[2048];
            int i = 0;
            while ((i = in.read(b)) != -1) {
                out.write(b, 0, b.length);
            }
            out.close();
            in.close();
            // java.util.Base64.getEncoder().encodeToString ==》对字节数组Base64编码
            return Base64.getEncoder().encodeToString(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    } 
}

02、使用

说明:将图片转成base64字符串以后 要加上前缀data:image/png;base64,

 	/**
     * 将本地 D:\img 下在百度logo 转成base64编码
     */
    @Test
    public void local_change(){
        //前缀
        String base64_prefix="data:image/png;base64,";
        //base64字符串
        String base64_str = ImgBase64Util.LocalImgToBase64("D:/img/baidu_Logo.png");
        //图片完整的编码
        String base64_file=base64_prefix+base64_str;
        //打印
        System.out.println("本地图片base完整字符串:"+"\n"+base64_file);
    }

效果:
在这里插入图片描述


将网络图片转base64字符串:

01、将文件读取封装成工具类

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author suqinyi
 * @Date 2021/4/23
 */
public class ImgBase64Util {
    /**
     * 将一张网络图片转成 Base64 字符串
     * 图片是GET请求
     * @param imgUrl 网络图片资源位置
     */
    public static String onlineImgToBase64(String imgUrl) throws Exception {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.setRequestMethod("GET");
            httpUrl.setConnectTimeout(30 * 1000);
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[2048];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return java.util.Base64.getEncoder().encodeToString(outStream.toByteArray());
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
    }
}

02、使用

 	/**
     * 将网络图片 --> base64编码
     * GET请求
     */
    @Test
    public void http_change() throws Exception {
        //百度Logo图片地址
        String imgUrl="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";
        //前缀
        String base64_prefix="data:image/png;base64,";
        //将图片转成base64字符串
        String base64_str = ImgBase64Util.onlineImgToBase64(imgUrl);
        //图片完整的编码
        String base64_file=base64_prefix+base64_str;
        //打印
        System.out.println("网络图片base完整字符串:"+"\n"+base64_file);
    }

效果:
在这里插入图片描述


前端使用

使用:img标签
在这里插入图片描述

效果:
在这里插入图片描述


完结

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

suqinyi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值