Android的 - BitmapFactory.de codeByteArray - OutOfMemoryError异常(OOM)异常、de、BitmapFactory、Android

2023-09-05 08:19:43 作者:你非良人、怎知我情深

我看过一篇文章关于OOM问题的100S。大部分都是关于大位图。我做一个地图应用程序,我们下载 256×256 天气覆盖瓦片。大多数是完全透明的,非常小的。我刚刚得到的,这是442个字节长,同时呼吁一个位图流崩溃 BitmapFactory.de codeByteArray(......)。

I have read 100s of article about the OOM problem. Most are in regard to large bitmaps. I am doing a mapping application where we download 256x256 weather overlay tiles. Most are totally transparent and very small. I just got a crash on a bitmap stream that was 442 Bytes long while calling BitmapFactory.decodeByteArray(....).

例外规定:

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

在code是:

The code is:

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;

}

下面是我在调试器中看到:

Here is what I see in the debugger:

bytesRead = 442

因此​​位图数据是442字节。为什么它试图创建一个23671KB位图和运行内存?

So the Bitmap data is 442 Bytes. Why would it be trying to create a 23671KB Bitmap and running out of memory?

推荐答案

我遇到了这样的问题,在过去。 Android使用位图虚拟机,​​这是非常小的。请确保您通过bmp.recycle处理位图。 Android的后续版本有更多的位图的VM,但我一直在处理这个版本有20MB的限制。

I have run into problems like this in the past. Android uses Bitmap VM and it is very small. Make sure you dispose your bitmap via bmp.recycle. Later versions of Android have more Bitmap VM but the version that I've been dealing with has a 20MB limit.