带有位图的Android Outofmemory异常

时间:2014-03-28 09:52:24

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

我有一个函数,它采用位图,两种颜色并返回一个BitmapDrawable:

// Theme function
    static public BitmapDrawable pFilter(Bitmap bitmap, int backgroundColor, int foregroundColor)
{

    Bitmap bitmapCopy = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), null, true);

    int[] pixels = new int[bitmapCopy.getByteCount()]; 

    bitmapCopy.getPixels(pixels, 0, bitmapCopy.getWidth(), 0, 0, bitmapCopy.getWidth(), bitmapCopy.getHeight());

    // Call native function

    bitmapCopy.setPixels(pixels, 0, bitmapCopy.getWidth(), 0, 0, bitmapCopy.getWidth(), bitmapCopy.getHeight());

    BitmapDrawable finalDrawable = new BitmapDrawable(Application.getAppContext().getResources(), bitmapCopy);

    return finalDrawable;
}

// Custom Imageview
public class CustomImageView extends ImageView 
{

private BitmapDrawable sourceImage;

private CustomTheme theme;

// [...]

private void refreshImageView()
{

  super.setImageDrawable(theme.pFilter(sourceImage.getBitmap(), theme.backgroundColor, theme.foregroundColor));

}

我的问题是,在大约80次调用此函数(使用10px * 10px位图)后,我在此行上获得了OutOfMemory异常:

int[] pixels = new int[bitmapCopy.getByteCount()]; 

感谢。

2 个答案:

答案 0 :(得分:0)

调用pFilter后(??);调用bitmap.recycle();在orignal位图上

答案 1 :(得分:0)

错误发生在我的JNI调用中,而不是在Android中:

(*env)->ReleaseIntArrayElements(env, pixels, nativePixels, JNI_COMMIT);
  

JNI_COMMIT:复制内容但不释放elems缓冲区

解决方案是使用0而不是JNI_COMMIT:

(*env)->ReleaseIntArrayElements(env, pixels, nativePixels, 0);