import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import sun.misc.BASE64Encoder;
public class Base64Utils {
private static Pattern pattern = Pattern.compile("\\s*|\t|\r|\n|");
/**
* 本地图片转为base64字符串,去除空格
* @Param imgFile 图片绝对路径
* @Author L_derek
*/
public static String photoToBase64RemoveBlank(String photoPath){
InputStream inputStream = null;
byte[] data = null;
//读取图片的字节数组
try{
inputStream = new FileInputStream(photoPath);
data = new byte[inputStream.available()];
inputStream.read(data);
}catch (IOException e){
e.printStackTrace();
}finally {
if (inputStream!= null){
try {
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
//对字节数组进行编码
BASE64Encoder base64Encoder = new BASE64Encoder();
return replaceBlankJson(base64Encoder.encode(data));
}
/**
* 本地图片转为base64字符串,不去除空格
* @Param imgFile 图片绝对路径
* @Author L_derek
*/
public static String photoToBase64NotRemoveBlank(String photoPath){
InputStream inputStream = null;
byte[] data = null;
//读取图片的字节数组
try{
inputStream = new FileInputStream(photoPath);
data = new byte[inputStream.available()];
inputStream.read(data);
}catch (IOException e){
e.printStackTrace();
}finally {
if (inputStream!= null){
try {
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
//对字节数组进行编码
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(data);
}
private static String replaceBlankJson(String encode) {
String s = "";
if (encode!=null){
Matcher matcher = pattern.matcher(encode);
s = matcher.replaceAll("");
}
return s;
}
}
图片转码为base64(可选择去除不去除空格)
最新推荐文章于 2023-08-07 14:29:31 发布