Java Base64編碼轉成圖片

package cn.bts.action.setting;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/** 
* 項目名稱:lecong_backend   
* 類  名  稱:TestImg   
* 類  描  述:Base 64編碼轉換成圖片
* 創  建  人:Seven   
* 創建時間:2014年11月11日 下午5:23:19   
* 修  改  人:Seven   
* 修改時間:2014年11月11日 下午5:23:19   
* 修改備註:   
* @version 1.0
*/
public class TestImg {

	public static void main(String[] args) {
		
		String img = "";//存放編碼
		GenerateImg(img, "E:\1.jpg");
		System.out.println(getImg("E:\1.jpg"));
		
	}
	
	//將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理
	public static String getImg(String imgPath){
		byte[] bytes = null;
		
		try{
			
			InputStream inputStream = new FileInputStream(imgPath);//將圖片轉換成字節數組
			bytes = new byte[inputStream.available()];
			inputStream.read(bytes);
			inputStream.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(bytes);
	}
	
	//對字節數組Base64編碼
	public static boolean GenerateImg(String str,String imgPath){//生成圖片
		boolean flag = true;
		BASE64Decoder decoder = new BASE64Decoder();
		try{
			if(str!=null){
				byte[] b = decoder.decodeBuffer(str);
				for (int i = 0; i < b.length; i++) {
					if(b[i]<0){
						b[i] +=256;
					}
				}
				OutputStream out = new FileOutputStream(imgPath);
				out.write(b);
				out.flush();
				out.close();
				flag = true;
			}else{
				System.out.println("Base64編碼不能爲null");
				flag = false;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return flag;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章