java base64字符与图片互转

 
 
  1. import java.io.FileInputStream;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6.   
  7. import sun.misc.BASE64Decoder;  
  8. 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);
}

猜你喜欢

转载自blog.csdn.net/J_M_S_H_T/article/details/80663295