1.base64的含义
2.base64的java转换
Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,在发送电子邮件时,服务器认证的用户名和密码需要用Base64编码,附件也需要用Base64编码。
Base64要求把每三个8Bit的字节转换为四个6Bit的字节(38 = 46 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。
原文的字节最后不够3个的地方用0来补足,转换时Base64编码用=号来代替。这就是为什么有些Base64编码会以一个或两个等号结束的原因,但等号最多只有两个。
public String querySignImage(Integer doctorId) {
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
if (doctorId != null){
//获取图片地址
String signImgUrl = baseMapper.selectById(doctorId).getSignImg();
//读取路径下面的文件(此文件路径为本机的绝对路径)
File file = new File(urlConstant.getRESOURCE_IMG_PATH() + urlConstant.getIMG_READ_PACKAGE().get(5) + signImgUrl.substring(signImgUrl.lastIndexOf('/')));
byte[] data = null;
try {
FileInputStream fileInputStream = new FileInputStream(file);
int available = fileInputStream.available();
data = new byte[available];
fileInputStream.read(data);
fileInputStream.close();
String trim = encoder.encodeBuffer(data).trim();
String s = trim.replaceAll("\n", "").replaceAll("\r", "");
String substring = signImgUrl.substring(signImgUrl.lastIndexOf('.')+1);
return "data:image/" + substring + ";base64,"+s;
} catch (IOException e) {
throw new ServiceException(e.getMessage());
}
}else {
throw new ServiceException("查询签名时医生id不能为空!");
}
}
说明这个BASE64Encoder 有可能随时被删除的可能所以网上建议apache commons.codec下的Base64替代。
引入依赖
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>${commons-codec.version}version>
dependency>
图片转成base64
public class base64Util {
//绝对路径
public String imgBase64(String url) {
String s = null;
String substring = url.substring(url.lastIndexOf('.')+1);
try {
//"E:/static-resource/ihospital/doctorSign/doctor_sign_img-1.png"
File imgFile = new File(url);
byte[] data = null;
FileInputStream fileInputStream = new FileInputStream(imgFile);
int available = fileInputStream.available();
data = new byte[available];
fileInputStream.read(data);
fileInputStream.close();
s = Base64.encodeBase64String(data);
s.replaceAll("\n", "").replaceAll("\r", "");
} catch (IOException e) {
e.printStackTrace();
}
return "data:image/" + substring + ";base64,"+ s;
}
}