關於android獲取網絡圖片主要是把網絡圖片的數據流讀入到內存中然後用
1.Bitmap bitMap = BitmapFactory.decodeByteArray(data, 0, length);
方法來將圖片流傳化為bitmap類型 這樣才能用到
1.imageView.setImageBitmap(bitMap);
來進行轉化
在獲取bitmap時候出現null
錯誤代碼:
byte[] data = GetImageForNet.getImage(path);
int length = data.length;
Bitmap bitMap = BitmapFactory.decodeByteArray(data, 0, length);
imageView.setImageBitmap(bitMap);
下面是 GetImageForNet.getImage()方法的代碼清單
public static byte[] getImage(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection httpURLconnection = (HttpURLConnection)url.openConnection();
httpURLconnection.setRequestMethod("GET");
httpURLconnection.setReadTimeout(6*1000);
InputStream in = null;
byte[] b = new byte[1024];
int len = -1;
if (httpURLconnection.getResponseCode() == 200) {
in = httpURLconnection.getInputStream();
in.read(b);
in.close();
return b;
}
return null;
}
看起來沒有問題 獲取網絡圖片輸入流,填充二進制數組,返回二進制數組,然後使用 Bitmap bitMap = BitmapFactory.decodeByteArray(data, 0, length); data就是返回的二進制數組
獲取bitMap 看起來沒有問題,可是bitMap就是為null!
BitmapFactory.decodeByteArray方法中所需要的data不一定是傳統意義上的字節數組,查看android api,最後發現BitmapFactory.decodeByteArray所需要的data字節數組並不是想象中的數組!而是把輸入流傳化為字節內存輸出流的字節數組格式
正確代碼:
try {
byte[] data = GetImageForNet.getImage(path);
String d = new String(data);
// File file = new File("1.jpg");
//OutputStream out = new FileOutputStream(file);
//out.write(data);
//out.close();
int length = data.length;
Bitmap bitMap = BitmapFactory.decodeByteArray(data, 0, length);
imageView.setImageBitmap(bitMap);
//imageView.seti
} catch (Exception e) {
Log.i(TAG, e.toString());
Toast.makeText(DataActivity.this, "獲取圖片失敗", 1).show();
}
下面是改進後的 GetImageForNet.getImage()方法的代碼清單
public static byte[] getImage(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection httpURLconnection = (HttpURLConnection)url.openConnection();
httpURLconnection.setRequestMethod("GET");
httpURLconnection.setReadTimeout(6*1000);
InputStream in = null;
byte[] b = new byte[1024];
int len = -1;
if (httpURLconnection.getResponseCode() == 200) {
in = httpURLconnection.getInputStream();
byte[] result = readStream(in);
in.close();
return result;
}
return null;
}
public static byte[] readStream(InputStream in) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
in.close();
return outputStream.toByteArray();
}
摘自 qingli518