java工具類-圖片和Base64互轉

圖片往往會轉成Base64進行網絡傳輸,持久化存儲等等。

Base64轉圖片:


	//base64字符串轉化成圖片  
    @SuppressWarnings("restriction")
	public static File GenerateImage(String imgStr,String fileDir,String fileName){   //對字節數組字符串進行Base64解碼並生成圖片
        if (imgStr == null) 
        	//圖像數據爲空  
            return null;
		BASE64Decoder decoder = new BASE64Decoder();
        //圖片的輸出流
        OutputStream imageOut = null;
        try{  
            //Base64解碼  
			byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i){  
                if(b[i]<0){
                	//調整異常數據  
                    b[i]+=256;
                }
            }
            //先判斷目錄是否存在
            File dir = new File(fileDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
            //如果文件不存在,則保存。如果存在則跳過?
			String realFilePath = fileDir+File.separator+fileName;
            File file = new File(realFilePath);
            if(!file.exists()){
            	//1.創建文件,作爲圖片的外殼;
            	file.createNewFile();
            	imageOut = new FileOutputStream(file);
        		imageOut.write(b);
        		imageOut.flush();
        		imageOut.close();
        		return file;
            }
            return file;
        }
        catch (Exception e){
        	e.printStackTrace();
            return null;
        }
    }  

圖片轉成Base64:


    //圖片轉化成base64字符串  
	//imgFile:文件路徑
    public static String GetImageStr(String imgFilePath){//將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理  
        InputStream in = null;  
        byte[] data = null;  
        //讀取圖片字節數組  
        try{  
            in = new FileInputStream(imgFilePath);          
            data = new byte[in.available()];  
            in.read(data);  
            in.close();  
        }   
        catch (IOException e){  
            e.printStackTrace();  
        }  
        //對字節數組Base64編碼  
        BASE64Encoder encoder = new BASE64Encoder();  
        return encoder.encode(data);//返回Base64編碼過的字節數組字符串  
    }  

 

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