前言:
Android手機(jī)客戶端的圖片數(shù)據(jù)上傳到服務(wù)器中保存,首先需要將客戶端的圖片轉(zhuǎn)換成Base64格式,然后才能通過(guò)網(wǎng)絡(luò)上傳到服務(wù)器中。
有兩種方法可以實(shí)現(xiàn):
讓客戶端將圖片上傳到服務(wù)器,將圖片的網(wǎng)絡(luò)URL告訴服務(wù)器
將圖片轉(zhuǎn)成Base64編碼,傳遞給服務(wù)器,服務(wù)器將Base64字符串解碼之后生成一張圖片。
本文就重點(diǎn)講解一下圖片轉(zhuǎn)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)
我們發(fā)現(xiàn),四個(gè)編碼方法都有一個(gè)flags參數(shù),這就是編碼標(biāo)志位,或者編碼標(biāo)準(zhǔn)。
編碼標(biāo)準(zhǔn)有以下幾種:
CRLF
Win風(fēng)格的換行符,意思就是使用CR和LF這一對(duì)作為一行的結(jié)尾而不是Unix風(fēng)格的LF。
CRLF是Carriage-Return Line-Feed的縮寫(xiě),意思是回車(\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代碼如下:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-426369.html
/**
* 將圖片轉(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()];
//寫(xiě)入數(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)圖片代碼如下:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-426369.html
/**
* 將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;
}
}
到了這里,關(guān)于Android中的圖片如何轉(zhuǎn)換成Base64格式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!