IDKit.RawImage bitmap2Raw(Bitmap bitmap) {

int width = bitmap.getWidth();

int height = bitmap.getHeight();

 

int[] pixels = new int[width * height];

bitmap.getPixels(pixels, 0, width, 0, 0, width, height);

byte[] pixelArray = new byte[pixels.length];

for(int i = 0; i <pixels.length ; i++) {

int pixel = pixels[i];

int A = Color.alpha(pixel);

int R = Color.red(pixel);

int G = Color.green(pixel);

int B = Color.blue(pixel);

pixelArray[i] = (byte) (0.2989 * R + 0.5870 * G + 0.1140 * B);

}

return new IDKit.RawImage(width,height,pixelArray);

}

Faster method without floating point arithmetic

public static IDKit.RawImage toRawImage(Bitmap bitmap)

{

int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];

byte[] grey = new byte[pixels.length];

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

for (int r = 0; r < bitmap.getHeight(); ++r) {

int offset = r * bitmap.getWidth();

for (int c = 0; c < bitmap.getWidth(); ++c) {

int color = pixels[offset + c];

grey[offset + c] = (byte) ((color & 0x0000FF00) >> 8); // just green channel

}

}

return new IDKit.RawImage(bitmap.getWidth(), bitmap.getHeight(), grey);

}