Base64对图片的编码和解码

public class test{


//图片转化成base64字符串
public static String GetImageStr(){

//将图片文件转化为字节数组字符串,并对其进行Base64编码处理 
String imgFile = "E:\\Image\\image.jpg";
//将图片转为字节数组
InputStream in = null;
byte[] data = null;


try {
//读取图片字节数组  
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//对字节数组base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);

}


//base64字符串转化成图片 

public static boolean GenerateImage(String imgStr) {

//对字节数组字符串进行Base64解码并生成图片  
if(imgStr==null) 
return false;


BASE64Decoder decoder = new BASE64Decoder();

try {

byte[] b = decoder.decodeBuffer(imgStr);

for(int i=0;i<b.length;i++) {

if(b[i]<0) {
b[i]+=256;
}

}

//生成jpeg图片
String imgpath = "E:\\image.jpg";


FileOutputStream out = new FileOutputStream(imgpath);
out.write(b);
out.flush();
out.close();
return true;


} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return false;

}
public static void main(String[] args)  
   {  
       String strImg = GetImageStr();  
       System.out.println(strImg);  
       GenerateImage(strImg);  
   }  


}
展开阅读全文

没有更多推荐了,返回首页