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());
}
}
图片转换为Base64
最新推荐文章于 2024-05-20 22:28:51 发布