0
我正在使用以下方法從url獲取位圖,但圖像未顯示。圖像是一個大約50x50px的png文件。謝謝。未顯示android遠程位圖
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input,null,options);
Log.e("Bitmap","returned");
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value.
int scale=1;
while(options.outWidth/scale/2>=REQUIRED_SIZE && options.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(input, null, o2);
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
這並不直接回答你的問題,但你可能想考慮重構你這樣做的方式。現在,您正在有效地從互聯網上檢索圖像兩次。這非常浪費資源。你仍然可以完成你想要的結果,但實際上只能從互聯網上檢索一次圖像。例如,將結果存儲到一個字節數組中,然後使用該字節數組來解碼位圖兩次,根據需要構建您的BitmapFactory.Options。 –
他沒有兩次讀取圖像。當設置'options.inJustDecodeBounds = true;'時,只會讀取圖像的前20個字節,以便讀取標題並將圖像大小/元數據寫入選項實例。 – asenovm
不夠公平,但是即使假設只發送了確切的字節數(例如,沿途沒有緩衝或壓縮),對於完全相同的資源背靠背進行兩個HTTP請求仍然是浪費的。 –