1. 解码BASE64
protected static String generateImage(String imgStr, String path) throws IOException {
int start = imgStr.indexOf("/");
int end = imgStr.indexOf(";");
String ext = "." + imgStr.substring(start + 1, end);
imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
SimpleDateFormat fileSdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String time = sdf.format(new Date());
String fileName = fileSdf.format(new Date()) + ext;
File file = new File("C:/file_upload/" + path + time);
if(!file.exists()){
file.mkdirs();
}
OutputStream out = new FileOutputStream(file + "/" + fileName);
out.write(b);
out.flush();
out.close();
String photo_address = path + time + "/" + fileName;
return photo_address;
}
2. BASE64加密
protected String getImageStr(String filePath) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(filePath);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}