packageutil;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.InputStream;importjava.io.OutputStream;importjava.util.Date;importorg.apache.commons.lang.StringUtils;importcom.alibaba.druid.util.Base64;/*** @description base64工具类
*@author**/
public classBase64Util {/*** @desctiption base64转图片 (默认存放Tomcat中upload_files下,默认格式png)
*@paramstrBase64(base64),path(相对路径存储路径),filename(文件名,默认为时间戳)
*@author
*/
public static booleanbase64ToPic(String strBase64,String path,String filename){if(StringUtils.isEmpty(strBase64)){
System.out.println("Base64为空");return false;
}
Date date= newDate();long datetime =date.getTime();
String catalina_base=System.getProperty("catalina.base");//上传文件保存位置
path =catalina_base+"/upload_files/"+path;
File f= newFile(path);if(!f.exists()){
f.mkdirs();
}
Base64 base= newBase64();byte[] b =base.base64ToByteArray(strBase64);for(int i=0;i
b[i]+=256;
}
}
String imgFilePath= path+"/"+datetime+".png";if(StringUtils.isNotEmpty(filename)){
imgFilePath= path+"/"+filename;
}try{
OutputStream out= newFileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Base64转图片失败");return false;
}return true;
}/*** @desctiption 图片转base64
*@parampicPath (文件路径)
*@author
*/
public staticString picToBase64(String picPath){
File f= newFile(picPath);if(!f.isDirectory()){
System.out.println("此文件路径无效!");return null;
}
InputStream in= null;byte[] data = null;try{
in= newFileInputStream(picPath);
data= new byte[in.available()];
in.read(data);
in.close();
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}
Base64 base= newBase64();
String base64=base.byteArrayToBase64(data);returnbase64;
}
}