【问题标题】:Bitmap Factory Error on InputStream DecodeInputStream 解码上的位图工厂错误
【发布时间】:2017-04-27 09:00:14
【问题描述】:

我正在尝试制作一个从 http 连接中获取图像的简单函数。它以前可以工作,现在它会抛出一些错误。我没有对代码进行任何更改。输入流也不为空。它正在返回预期的数据。

D/skia: ---- read threw an exception
D/skia: --- SkAndroidCodec::NewFromStream returned null
I/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference

这是我在异步任务中的参考代码:

@Override
protected Bitmap doInBackground(String... url){
    try {
        InputStream in = openHttpConnection(url[0]);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
        in.close();
        return bitmap;
    } catch (IOException e) {
        Log.i("ERROR", e.toString());
        return null;
    }
}

private static InputStream openHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
        httpConn.disconnect();
    } catch (Exception e) {
        Log.i("ERROR", e.toString());
        throw new IOException("Error connecting");
    }
    return in;
}

【问题讨论】:

  • 它之前工作过然后恢复更改......我赌httpConn.disconnect();在你开始阅读输入流之前
  • Null 对象是我无法访问的代码中的静态类。为清楚起见,输入流不会返回 null。
  • 之前已经说过httpConn.disconnect();。删除它。它以前从来没有工作过。

标签: java android bitmap urlconnection


【解决方案1】:
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);

在此语句之后bitmap 为空。如果您要求 decodeStream 仅对边界进行解码,它将始终如此。

稍后您尝试使用 `bitmap.Compress() 压缩该空位图。

是否在静态函数中并不重要。

如果 bitmap==null 就不要调用它。

【讨论】:

  • Bitmap Compress 是从 DecodeStream 调用的,我不调用它。
  • 没有。一点也不。当您尝试使用位图时,它会在稍后被调用。您没有告诉您要对下载的图像做什么。保存到文件?请确认 bitmap== null 并且您盲目使用 null 对象/指针。
  • 你说得对,但我还是不明白为什么我的http请求在这里失败了?我可能会为了将来的毕加索之类的东西而放弃它。
  • 您的 http 请求根本没有失败。是什么让你这么想的?位图为空,因为您只是解码边界。
猜你喜欢
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 2013-07-20
相关资源
最近更新 更多