android - BitmapFactory.decodeStream 无一异常(exception)地返回 null

标签 android bitmapfactory

我尝试从服务器加载远程图像,感谢 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表示错误,但没有抛出Exception,所以我也说不清哪里出了问题。 InputStream 始终返回一个有效值,我知道该图片存在于服务器上。

祝你好运, 丹尼尔

最佳答案

我找到了答案 here并将获取方法更新为:

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;
}

关于android - BitmapFactory.decodeStream 无一异常(exception)地返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4414839/

相关文章:

Android普通按钮变透明

android - 有没有更好的方法可以在协程中设置n次监听器?

android - 下载外部 PNG 图像时丢失透明背景

android - 如何在不影响位图大小的情况下降低位图质量

android - 如何设置在 ListPreference 中选中的值

自定义首选项中的android首选项水平分隔线?

android - 通过 USB : The device is temporarily restricted 安装应用程序

android - BitmapFactory.decodeStream(InputStream is) 在 Android 上为非 null InputStream 返回 null

android - 下载图像并将其存储在 ContentProvider 中

android - NullPointerException 从文件 Android 重新缩放位图