图片转换为Base64

package cn.cloud.bs.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

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

public class FileToBase64 {
    public static String readImg(String urlOrPath){
        InputStream in = null;
        try {
            byte[] b ;
            //加载https途径的图片(要避开信任证书的验证)
            if(urlOrPath.toLowerCase().startsWith("https")){
                b=HttpsUtils.doGet(urlOrPath);
            }else if(urlOrPath.toLowerCase().startsWith("http")){
                //加载http途径的图片
                URL url = new URL(urlOrPath);
                in = url.openStream();
                b = getByte(in); //调用方法,得到输出流的字节数组

            }else{ //加载本地路径的图片
                File file = new File(urlOrPath);
                if(!file.isFile() || !file.exists() || !file.canRead()){
                    return "error";
                }
                in = new FileInputStream(file);
                b = getByte(in); //调用方法,得到输出流的字节数组

            }
            String base64Str = base64ToStr(b).replaceAll("\r|\n", "");

            String fileType = urlOrPath.substring(urlOrPath.lastIndexOf(".")+1);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("data:image/").append(fileType).append(";base64,").append(base64Str);

            return stringBuilder.toString();    //调用方法,为防止异常 ,得到编码后的结果

        } catch (Exception e) {
            return "error";
        }
    }

    public static byte[] getByte(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            byte[] buf=new byte[1024]; //缓存数组
            while(in.read(buf)!=-1){ //读取输入流中的数据放入缓存,如果读取完则循环条件为false;
                out.write(buf); //将缓存数组中的数据写入out输出流,如果需要写到文件,使用输出流的其他方法
            }
            out.flush();
            return out.toByteArray();	//将输出流的结果转换为字节数组的形式返回	(先执行finally再执行return	)
        } finally{
            if(in!=null){
                in.close();
            }
            if(out!=null){
                out.close();
            }
        }
    }

    /*
     * 编码
     * Base64被定义为:Base64内容传送编码被设计用来把任意序列的8位字节描述为一种不易被人直接识别的形式
     */
    public static String base64ToStr(byte[] bytes) throws IOException {
        String content = "";
        content = new BASE64Encoder().encode(bytes);
        return content.trim().replaceAll("\n", "").replaceAll("\r", ""); //消除回车和换行
    }
    /*
     * 解码
     */
    public static byte[] strToBase64(String content) throws IOException {
        if (null == content) {
            return null;
        }
        return new BASE64Decoder().decodeBuffer(content.trim());
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值