Skip to content

Instantly share code, notes, and snippets.

@dawsontoth
Created November 29, 2011 16:48
Show Gist options
  • Save dawsontoth/1405482 to your computer and use it in GitHub Desktop.
Save dawsontoth/1405482 to your computer and use it in GitHub Desktop.
How to take a Bitmap (in RGB) and grab the luminance values for YUV. Useful for passing an image to ZXing for processing.
public void handleBitmap(Bitmap image) {
int w = image.getWidth(), h = image.getHeight();
int[] rgb = new int[w * h];
byte[] yuv = new byte[w * h];
image.getPixels(rgb, 0, w, 0, 0, w, h);
populateYUVLuminanceFromRGB(rgb, yuv, w, h);
}
// Inspired in large part by:
// http://ketai.googlecode.com/svn/trunk/ketai/src/edu/uic/ketai/inputService/KetaiCamera.java
private void populateYUVLuminanceFromRGB(int[] rgb, byte[] yuv420sp, int width, int height) {
for (int i = 0; i < width * height; i++) {
float red = (rgb[i] >> 16) & 0xff;
float green = (rgb[i] >> 8) & 0xff;
float blue = (rgb[i]) & 0xff;
int luminance = (int) ((0.257f * red) + (0.504f * green) + (0.098f * blue) + 16);
yuv420sp[i] = (byte) (0xff & luminance);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment