bitmapfactory.decodestream返回null毫无例外
-
08-10-2019 - |
题
我尝试从服务器加载远程图像,并且由于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,它表示错误,但也没有例外,所以我无法真正分辨出出了什么问题。 InputStream始终返回一个有效的值,我知道该图片存在于服务器上。
最良好的祝福,丹尼尔
解决方案
我找到了答案 这里 并将获取方法更新为:
private static InputStream fetch(String address) throws MalformedURLException,IOException {
HttpGet httpRequest = new HttpGet(URI.create(address) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
return instream;
}
不隶属于 StackOverflow