根據圖片路徑把圖片的二進位制資料寫入記憶體
阿新 • • 發佈:2019-02-13
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//建立一個Buffer字串
byte[] buffer = new byte[1024];
//每次讀取的字串長度,如果為-1,代表全部讀取完畢
int len = 0;
//使用一個輸入流從buffer裡把資料讀取出來
while( (len=inStream.read(buffer)) != -1 ){
//用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度
outStream.write(buffer, 0, len);
}
//關閉輸入流
inStream.close();
//把outStream裡的資料寫入記憶體
return outStream.toByteArray();
}
/**
* 根據圖片路徑得到圖片的二進位制資料
* @param path
* @return
* @throws Exception
*/
public static byte[] getArrayByUrl(String path) throws Exception{
URL url = new URL(path);
// 開啟連線
URLConnection con = url.openConnection();
//設定請求超時為5s
con.setConnectTimeout(5*1000);
// 輸入流
InputStream inStream = con.getInputStream();
byte[] data = readInputStream(inStream);
return data;
}
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//建立一個Buffer字串
byte[] buffer = new byte[1024];
//每次讀取的字串長度,如果為-1,代表全部讀取完畢
int len = 0;
//使用一個輸入流從buffer裡把資料讀取出來
while( (len=inStream.read(buffer)) != -1 ){
//用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度
outStream.write(buffer, 0, len);
}
//關閉輸入流
inStream.close();
//把outStream裡的資料寫入記憶體
return outStream.toByteArray();
}
/**
* 根據圖片路徑得到圖片的二進位制資料
* @param path
* @return
* @throws Exception
*/
public static byte[] getArrayByUrl(String path) throws Exception{
URL url = new URL(path);
// 開啟連線
URLConnection con = url.openConnection();
//設定請求超時為5s
con.setConnectTimeout(5*1000);
// 輸入流
InputStream inStream = con.getInputStream();
byte[] data = readInputStream(inStream);
return data;
}