8
我嘗試從服務器加載遠程圖像,並感謝在stackoverflow上的很多代碼示例我有一個解決方案,在3個圖像中的2箇中工作。我真的不知道第三張圖片有什麼問題,有時讓代碼在調試器中運行時會加載圖片。另外,如果我先加載問題圖片,另外兩張圖片有時不加載。BitmapFactory.decodeStream毫無例外地返回null
下面是代碼:
public static Drawable getPictureFromURL(Context ctx, String url, final int REQUIRED_SIZE) throws NullPointerException {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
int scale = 1;
if (o.outWidth > REQUIRED_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(REQUIRED_SIZE/(double) Math.max(o.outHeight, o.outWidth))/Math.log(0.5)));
}
Log.i(Prototype.TAG, "scale: "+scale);
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bmp;
try {
bmp = BitmapFactory.decodeStream((InputStream) Tools.fetch(url), null, o2);
if(bmp!=null)
return new BitmapDrawable(ctx.getResources(), bmp);
else
return null;
} catch (Exception e) {
Log.e(Prototype.TAG, "Exception while decoding stream", e);
return null;
}
}
在調試過程中,我發現,o.outWidth是-1,表示錯誤,但不會引發任何異常,所以我真的不能告訴什麼地方出了錯。 InputStream總是返回一個有效的值,並且我知道該圖片存在於服務器上。
最良好的祝願, 丹尼爾
+1,但現在看來這些圖像是順序而不是並行下載(我將每個圖像放在一個單獨的AsyncTask上)。至少它工作.. – kellogs 2011-04-15 15:33:46