1.将图片进行Base64编码处理
File img = new Fie("D:\\Image\\001.png");
InputStream ins = null;
byte[] data = null;
//读取图片字节数组
try {
ins = new FileInputStream(img);
data = new byte[ins.available()];
ins.read(data);
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
System.out.println(encoder.encode(data));
2.Base64编码处理转化为图片
//base64转化为图片存储在指定的
String base64 = encoder.encode(data);
String fileName = "c001.png";
String filePath = "E:\\";
if(base64.contains("data:image")){
ase64 = base64.substring(base64.indexOf(",")+1);
}
base64 = base64.toString().replace("\r\n", "");
File file = null;
//创建文件目录
File dir=new File(filePath);
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
FileOutputStream fos = null;
OutputStream out = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(base64);
file=new File(filePath+fileName);
out = new FileOutputStream(filePath+fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
}catch (Exception e) {
e.printStackTrace();
}finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}