圖片轉換成Base64編碼的字符串

public class ImageBase64 {

    /**
     * 將圖片轉換成Base64編碼的字符串
     * @param path
     * @return base64編碼的字符串
     */
    public static String imageToBase64(String path){
        if(path.isEmpty()){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //創建一個字符流大小的數組。
            data = new byte[is.available()];
            //寫入數組
            is.read(data);
            //用默認的編碼格式進行編碼
            result = Base64.encodeToString(data,Base64.DEFAULT);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    /**
     *base64編碼字符集轉化成圖片文件。
     * @param base64Str
     * @param path 文件存儲路徑
     * @return 是否成功
     */
    public static boolean base64ToFile(String base64Str,String path){
        byte[] data = Base64.decode(base64Str,Base64.DEFAULT);
        for (int i = 0; i < data.length; i++) {
            if(data[i] < 0){
                //調整異常數據
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }

    }



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