- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
//base64字符串转化成图片
public static boolean base64ToImage(String base64Code, String path){
try{
//图像数据为空
if(base64Code == null)
return false;
//解码
byte[] b = new BASE64Decoder().decodeBuffer(base64Code);
for(int i = 0; i < b.length; i++){
//调整异常
if(b[i] < 0){
b[i] += 256;
}
}
//生成图片
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
}catch (Exception e) {
return false;
}
}
注:解码时要去掉字符串中的头部"data:image/jpeg;base64,"
//图片保存为base64
public static String imageToBase64(String imagePath){
//将图片文件转为字节数组字符串,并对其进行base64编码处理
InputStream in = null;
byte[] b = null;
try{
in = new FileInputStream(imagePath);
b = new byte[in.available()];
in.read(b);
in.close();
}catch (Exception e) {
e.printStackTrace();
return null;
}
//对字节数组编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(b);
}