Android – BitmapFactory.decodeByteArray – OutOfMemoryError(OOM)

我已经阅读了100篇关于OOM问题的文章.大多数是关于大位图.我正在做一个地图应用程序,我们下载256×256天气覆盖瓷砖.大多数是完全透明的,非常小.我刚刚在调用BitmapFactory.decodeByteArray(….)的位图流上遇到了442字节的崩溃.

例外情况说明:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=9415KB, Allocated=5192KB, Bitmap Size=23671KB)

代码是:

protected Bitmap retrieveImageData() throws IOException {
    URL url = new URL(imageUrl);
    InputStream in = null;
    OutputStream out = null;
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // determine the image size and allocate a buffer
    int fileSize = connection.getContentLength();
    if (fileSize < 0) {
        return null;
    }
    byte[] imageData = new byte[fileSize];

    // download the file
    //Log.d(LOG_TAG, "fetching image " + imageUrl + " (" + fileSize + ")");
    BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());
    int bytesRead = 0;
    int offset = 0;
    while (bytesRead != -1 && offset < fileSize) {
        bytesRead = istream.read(imageData, offset, fileSize - offset);
        offset += bytesRead;
    }

    // clean up
    istream.close();
    connection.disconnect();
    Bitmap bitmap = null;
    try {
        bitmap = BitmapFactory.decodeByteArray(imageData, 0, bytesRead);
    } catch (OutOfMemoryError e) {
        Log.e("Map", "Tile Loader (241) Out Of Memory Error " + e.getLocalizedMessage());
        System.gc();
    }
    return bitmap;

}

这是我在调试器中看到的:

bytesRead = 442

所以位图数据是442字节.为什么要尝试创建23671KB位图并耗尽内存?

最佳答案 我过去遇到过这样的问题. Android使用Bitmap VM,它非常小.确保通过bmp.recycle处理位图. Android的更高版本有更多的Bitmap VM,但我一直在处理的版本有20MB的限制.

点赞