BASE64和其他相似的编码算法通常用于转换二进制数据为文本数据,其目的是为了简化存储或传输。更具体地说,BASE64算法主要用于转换二进制数据为ASCII字符串格式。Java语言提供了一个非常好的BASE64算法的实现,即Apache Commons Codec工具包。本文将简要地讲述怎样使用BASE64以及它是怎样工作的。
下面我们用BASE64对字符串进行编码:
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;
/**
* 通过 Base64 对图片进行加密和解密
* @author zhangtengda
* @version 1.0
* @created 2015年6月15日 下午1:12:27
*/
public class Base64Utils {
public static void main(String[] args) throws Exception {
String str = "helloWorld";
byte[] encodeBase64 = Base64.encodeBase64(str.getBytes());
System.out.println("result " + new String(encodeBase64));
byte[] decodeBase64 = Base64.decodeBase64(encodeBase64);
System.out.println(new String(decodeBase64));
// String imagePath = "D:\\bz.jpg";
// String imageStr = getImageStr(imagePath);
// System.out.println(imageStr);
// saveImage(imageStr);
}
/**
* 描述:获取图片的 base64 编码后的 string
* <pre>
* 举例:
* </pre>
* @param imagePath
* @return
* @throws Exception
*/
public static String getImageStr(String imagePath) throws Exception {
Base64 base = new Base64();
byte[] data = null;
InputStream in = new FileInputStream(imagePath);
data = new byte[in.available()];
in.read(data);
in.close();
return base.encodeToString(data);
}
/**
* 描述:保存 Base64 编码字符串为图片
* <pre>
* 举例:
* </pre>
* @param byteImage
* @throws IOException
*/
public static void saveImage(String imageStr) throws IOException{
Base64 base = new Base64();
String ctxPath = "D:\\";
byte[] imgaeBytes = base.decode(imageStr);
File newFile = new File((ctxPath + "test.jpg").trim());
OutputStream out =new FileOutputStream(newFile);//获取输出字节流
BufferedOutputStream bos=new BufferedOutputStream(out);//带缓冲的输出字节流
DataOutputStream dos=new DataOutputStream(bos);//带缓冲的输出字节流,支持写java的基本数据类型
dos.write(imgaeBytes);
dos.close();
bos.close();
out.close();
}
}