Base64 编码 解码

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();
	}
	
	
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值