我尝试从服务器加载远程图片,感谢stackoverflow上的许多代码示例,我有了一个解决方案可以在3张图片中的2张工作。我不知道第三张图片的问题是什么,有时在调试器中运行代码时,图片会被加载。如果我首先加载有问题的图片,则其他两张图片有时无法加载。
以下是代码:
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,这表示出现了错误,但没有抛出异常,所以我无法确定具体出了什么问题。输入流始终返回有效值,并且我知道图片在服务器上存在。
祝好, Daniel