Android實(shí)現(xiàn)將圖片轉(zhuǎn)換上傳服務(wù)器功能
讓客戶端將圖片上傳到服務(wù)器,將圖片的網(wǎng)絡(luò)URL告訴服務(wù)器
將圖片轉(zhuǎn)成Base64編碼,傳遞給服務(wù)器,服務(wù)器將Base64字符串解碼之后生成一張圖片。
Android在util包中提供了android.util.Base64類
該類提供了四個(gè)編碼方法,分別是:
public static byte[] encode(byte[] input, int flags)public static byte[] encode(byte[] input, int offset, int len, int flags)public static String encodeToString(byte[] input, int flags)public static String encodeToString(byte[] input, int offset, int len, int flags)
提供了三個(gè)解碼
public static byte[] decode(String str, int flags)public static byte[] decode(byte[] input, int flags)public static byte[] decode(byte[] input, int offset, int len, int flags)
CRLF
Win風(fēng)格的換行符,意思就是使用CR和LF這一對(duì)作為一行的結(jié)尾而不是Unix風(fēng)格的LF。CRLF是Carriage-Return Line-Feed的縮寫,意思是回車(\r)換行(\n)。也就是說(shuō),Window風(fēng)格的行結(jié)束標(biāo)識(shí)符是\r\n,Unix風(fēng)格的行結(jié)束標(biāo)識(shí)符是\n。
DEFAULT
這個(gè)參數(shù)是默認(rèn),使用默認(rèn)的方法來(lái)加密NO_PADDING
這個(gè)參數(shù)是略去加密字符串最后的“=”NO_WRAP
這個(gè)參數(shù)意思是略去所有的換行符(設(shè)置后CRLF就沒(méi)用了)URL_SAFE
這個(gè)參數(shù)意思是加密時(shí)不使用對(duì)URL和文件名有特殊意義的字符來(lái)作為加密字符,具體就是以-和_取代+和/。NO_CLOSE
通常與`Base64OutputStream`一起使用,是傳遞給`Base64OutputStream`的標(biāo)志指示它不應(yīng)關(guān)閉正在包裝的輸出流。圖片轉(zhuǎn)Base64代碼如下:
/*** 將圖片轉(zhuǎn)換成Base64編碼的字符串*/public static String imageToBase64(String path){if(TextUtils.isEmpty(path)){return null;}InputStream is = null;byte[] data = null;String result = null;try{is = new FileInputStream(path);//創(chuàng)建一個(gè)字符流大小的數(shù)組。data = new byte[is.available()];//寫入數(shù)組is.read(data);//用默認(rèn)的編碼格式進(jìn)行編碼result = Base64.encodeToString(data,Base64.NO_CLOSE);}catch (Exception e){e.printStackTrace();}finally {if(null !=is){try {is.close();} catch (IOException e) {e.printStackTrace();}}}return result;}
Base64轉(zhuǎn)圖片代碼如下:
/*** 將Base64編碼轉(zhuǎn)換為圖片* @param base64Str* @param path* @return true*/public static boolean base64ToFile(String base64Str,String path) {byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);for (int i = 0; i < data.length; i++) {if(data[i] < 0){//調(diào)整異常數(shù)據(jù)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;}}
評(píng)論
圖片
表情
