InputStream解码的位图工厂错误

时间:2017-04-27 09:00:14

标签: java android bitmap urlconnection

我正在尝试创建一个从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;
}

1 个答案:

答案 0 :(得分:0)

options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);

此语句后bitmap为空。如果你要求decodeStream只解码边界,那将永远如此。

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

这是否属于静态函数并不重要。

如果位图== null,请不要调用它。