天天看點

圖檔與Base64字元串互相轉化

/**
* 圖檔轉化成base64字元串  
* @param imgFilePath 待處理的圖檔
* @return
*/
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();
        try 
        {
            if(in!=null)
            in.close();
        } 
        catch (Exception e2) 
        {
            e2.printStackTrace();
        }
    }  
    //對位元組數組Base64編碼  
    BASE64Encoder encoder = new BASE64Encoder();  
    return encoder.encode(data);//傳回Base64編碼過的位元組數組字元串  
}  

/**
* base64字元串轉化成圖檔  
* @param imgStr
* @return
*/
public static boolean GenerateImage(String imgStr,String saveImgFilePath)  
{   
    //對位元組數組字元串進行Base64解碼并生成圖檔  
    if (imgStr == null) //圖像資料為空  
    return false; 

    OutputStream out = null;
    try   
    {  
        //Base64解碼  
        BASE64Decoder decoder = new BASE64Decoder();  
        byte[] b = decoder.decodeBuffer(imgStr);  
        for(int i=;i<b.length;++i)  
        {  
            if(b[i]<)  
              b[i]+=;//調整異常資料  
        }  
        //生成jpeg圖檔  
        out = new FileOutputStream(saveImgFilePath);      
        out.write(b);  
        out.flush();  
        out.close();  
        return true;  
    }   
    catch (Exception e)   
    {  
        e.printStackTrace();
        try 
        {
            if(out!=null)
            {
                out.flush();  
                out.close();
            }
        } 
        catch (Exception e2) 
        {
            e2.printStackTrace();
        }
        return false;  
    }  
}