Skip to content

Instantly share code, notes, and snippets.

@moondroid
Created March 12, 2015 09:15
Show Gist options
  • Select an option

  • Save moondroid/c824ae418e83669583ff to your computer and use it in GitHub Desktop.

Select an option

Save moondroid/c824ae418e83669583ff to your computer and use it in GitHub Desktop.
Transform Bitmap to grayscale
public static Bitmap toGrayScale(Bitmap bmpOriginal) {
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
bmpOriginal.recycle();
return bmpGrayscale;
}
@arifbd

arifbd commented Jun 10, 2018

Copy link
Copy Markdown

I use your method, but i got this error on (Samsung Galaxy Grand Prime, 1024MB RAM, Android 5.0) and (Samsung Galaxy J7, 1536MB RAM, Android 6.0)

java.lang.OutOfMemoryError:
...
...
...
at packageName.toGrayscale (Conversions.java:32)
...
...
...

the code of 32 no lines are given below.
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

please help me. Thank you in advance!

@rayworks

rayworks commented Aug 9, 2018

Copy link
Copy Markdown

@arifbd
It seems the original bitmap is quite large. Please check the width and height before you call the method Bitmap.createBitmap(...).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment