反转位图时的OutOfMemory?

时间:2012-10-17 09:11:57

标签: android android-viewpager out-of-memory

我在反转位图时出现OutOfMemory错误。以下是我用来反转的代码:

public Bitmap invertBitmap(Bitmap bm) {
        Bitmap src = bm.copy(bm.getConfig(), true);

        // image size
        int height = src.getHeight();
        int width = src.getWidth();
        int length = height * width;
        int[] array = new int[length];
        src.getPixels(array, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight());
        int A, R, G, B;
        for (int i = 0; i < array.length; i++) {
            A = Color.alpha(array[i]);

            R = 255 - Color.red(array[i]);
            G = 255 - Color.green(array[i]);
            B = 255 - Color.blue(array[i]);

            array[i] = Color.argb(A, R, G, B);
        }
        src.setPixels(array, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight());

        return src;
    }

图像大约80 kb,尺寸为800x1294,图片中有黑色和不可见背景的文字。
图像位于ViewPager ..

3 个答案:

答案 0 :(得分:0)

复制bm时,请尝试:bm = null;

答案 1 :(得分:0)

在android中,由于16MB(在几乎所有手机上)应用程序的内存上限,将整个位图保存在内存中是不明智的。这是一种常见情况,可能会发生在开发人员身上。

您可以在this stackoverflow线程中获取有关此问题的许多信息。但我真的很恳请你阅读有关有效使用Bitmaps的android官方文档。它们是herehere

答案 2 :(得分:0)

图像使用的内存大小与该图像的文件大小完全不同。

在文件中,图像可以使用不同的算法(jpg,png等)进行压缩,当作为位图加载到内存中时,每个像素使用2或4个字节。

因此,在您的情况下(您不是播放代码,但它像每个像素使用4个字节一样),每个图像的内存大小为:

size = width * height * 4; // this is aprox 2MB

在代码中,首先将原始位图复制到新位图,然后停止数组以操作颜色。因此,每次图像反转总共使用size x 3 = 6MB

有很多关于如何在Android中处理大型位图的示例,但我会告诉您我认为最重要的主题:

  • 尝试在上面的代码中仅使用一个位图副本
  • 如果您的图片中只有单词,请使用Bitmap.Config = RGB_565。这仅使用每像素2个字节,将大小减小一半。
  • 在您不再需要的位图上调用recycle()
  • Bitmap.Factory中有一个大规模的lool选项。您可以减小仍然符合您需求的图像尺寸。
祝你好运。