1. base64转图片并保存在路径目录下
public static String base64ToImg(String img, String operateId){
BASE64Decoder decoder = new BASE64Decoder();
//Base64解码
byte[] b = new byte[0];
//图片完整路径 注意:目录下一定要加一个文件格式不然图片字节输出不了
String elbowPhotoImgpath ="G:\\imgpath\\"+operateId+".png";
try {
b = decoder.decodeBuffer(img);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{
//调整异常数据
b[i]+=256;
}
}
OutputStream out = new FileOutputStream(elbowPhotoImgpath);
out.write(b);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return elbowPhotoImgpath;
}
注:base64转图片时需要把“data:image/jpeg;base64,”删掉。不然图片是坏的。
2.图片转base64字符串
/**
* 图片转base64字符串
* @param imgPath
* @return
*/
public static String imgTobase64(String imgPath){
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgPath);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}