4

我已经阅读了 100 篇关于 OOM 问题的文章。大多数是关于大位图的。我正在做一个地图应用程序,我们在其中下载256x256天气叠加图块。大多数都是完全透明的并且非常小。我刚刚在调用时遇到了 442 字节长的位图流崩溃BitmapFactory.decodeByteArray(....).

例外规定:

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 位图并耗尽内存?

4

3 回答 3

2

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

于 2011-09-03T04:06:41.693 回答
0

听起来您已经阅读了有关此主题的一些内容,因此我将省略标准的“这就是您解码位图的方式”评论。

它突然出现在我身上,您可能正在保留对旧位图的引用(可能图块已移出屏幕,但您仍然在某处的数组中有引用,因此它没有被垃圾收集?) . 这在过去让我非常痛苦 - 内存泄漏很难调试。

这里有一个很棒的Google I/O 视频,当我遇到类似问题时,它对我很有帮助。大约一个小时,但希望能在几天后为您节省时间。它涵盖了以下内容:

  1. 创建堆转储
  2. DDMS 中的堆使用情况
  3. 使用 MAT 比较/分析堆转储
于 2014-02-01T20:19:33.590 回答
0

这可能有效。将位图缩小到较低质量。我不确定,但这可能会复制内存中的图像,但很容易值得一试。

            Bitmap image;
   image = BitmapFactory.decodeByteArray(data, 0, data.length);
   Bitmap mutableBitmap = image.copy(Bitmap.Config.ARGB_4444, true);
   Canvas canvas = new Canvas(mutableBitmap); 

我认为下面的旧答案不会流式传输。

                Options options = new BitmapFactory.Options();
        Options options2 = new BitmapFactory.Options();
        Options options3 = new BitmapFactory.Options();

        options.inPreferredConfig = Bitmap.Config.ARGB_8888;///////includes alpha
        options2.inPreferredConfig = Bitmap.Config.RGB_565 ;///////no alpha
        options3.inPreferredConfig = Bitmap.Config.ARGB_4444 ;/////alpha lesser quality

        image=BitmapFactory.decodeResource(getResources(),R.drawable.imagename,options); 
        image=Bitmap.createScaledBitmap(image, widthx,height, true);  
于 2012-09-13T01:51:50.593 回答