InputStream 解码时出现位图工厂错误

Bitmap Factory Error on InputStream Decode

我正在尝试制作一个从 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;
}
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);

这条语句后bitmap为空。如果你要求 decodeStream 只解码边界,它总是如此。

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

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

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