1.需要取到blank.png图片文件,我的目录结构如下:
2.取blank.png的路径,两种方式:
以两个不同路径为例:一种放在resources下,一种放在webapp下。
//两种方式
//1.取resources目录下的template目录下的blank.png文件
String a3=ReportViewAction.class.getResource("/").getPath().toString();
// a3:/R:/work/hh/dsh/travelReport/target/travelReport/WEB-INF/classes/
String url = a3+"template/blank.png";
// url:/R:/work/hh/dsh/travelReport/target/travelReport/WEB-INF/classes/template/blank.png
LOGGER.info("****************a3:{}",a3);
LOGGER.info("****************url1:{}",url);
//2.取webapp目录下images下的blank.png文件
String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
// t:/R:/work/hh/dsh/travelReport/target/travelReport/WEB-INF/classes/
String t0 = t.replaceAll("WEB-INF/classes/", "");
String t1 = t0+"images/blank.png";
// t1:/R:/work/hh/dsh/travelReport/target/travelReport/images/blank.png
LOGGER.info("****************t1:{}",t1);
//这里使用第一种方式
String blankEncode = reportViewService.getImageStr(url);
3.将图片用BASE64Encoder转码方法如下:
/**
* 获取文件Base64字节码字符串
* @param url
* @return
*/
public String getImageStr(String url) {
InputStream in = null;
byte[] data = null;
File file = new File(url);
try {
in = new FileInputStream(file);
data = new byte[in.available()];
in.read(data);
in.close();
BASE64Encoder encoder = new BASE64Encoder();
String encodeData = encoder.encode(data);
return encodeData;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
其他可能用到的方法:
1.Base64字符串转为字节数组
/**
* Base64字符串转为字节数组
* @param encodeData
* @return
*/
public byte[] baseTobyte(String encodeData) {
byte[] data;
try {
//解码
BASE64Decoder decoder = new BASE64Decoder();
data = decoder.decodeBuffer(encodeData);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2.Base64字节数组转为文件
/**
* Base64字节数组转为文件
* @param model
* @throws IOException
*/
public void baseToFile(Map<String, Object> model) throws IOException {
//此处为获取Base64位的字节码字符串
String encodeData = model.get("model_pic").toString();
//此处为输出文件路径全名/D:/word/word.doc
String path = model.get("path").toString();
//此处为输出文件路径文件夹/D:/word/
String dirPath = path.substring(0,path.lastIndexOf(SEPARATOR)+1);
File tempPath = new File(dirPath);
if (!tempPath.exists()) {
tempPath.mkdirs();
}
//调用字节码字符串转为字节码数组方法 ,得到字节码数组
byte[] fileEncode = baseTobyte(encodeData);
//输出文件
FileOutputStream fos= new FileOutputStream(path);
fos.write(fileEncode);
fos.flush();
fos.close();
}