What I am trying to do, is to take a photo using a camera intent, retrieve and convert said photo to a grayscale byte array (note: I am not interested in getting a grayscale image, just need the byte data). Then finally, apply a threshold and average all the pixels above the threshold.
The relevant snippet of code is:
@Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream stream = null;
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
try {
stream = getContentResolver().openInputStream(data.getData());
bmp = BitmapFactory.decodeStream(stream);
bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
for(int x = 0; x < bmp.getWidth(); ++x) {
for(int y = 0; y < bmp.getHeight(); ++y) {
int index = y * bmp.getWidth() + x;
int R = (pixels[index] >> 16) & 0xff;
int G = (pixels[index] >> 8) & 0xff;
int B = (pixels[index]) & 0xff;
double Grey = (0.299 * R + 0.587 * G + 0.114 * B);
if(Grey > 20) {
sum += Grey;
count++;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//Toast.makeText(this, "Image saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
double Y = sum / count;
The toast comment is there for testing, I used that earlier to make sure the intent was working - it was, but the path it gave was
Content://media/external/images/media/##
(where ## is the next photo number).
I have tried this in the Eclipse emulator, and I get a RuntimeException error at where the bitmap starts. I get a similar crash when I do a live test on an LG Optimus L3 (Android version 2.3.6).
I am convinced I have goofed up somewhere in the bitmap part of the code (and yes, I have read the developers guide and several threads here and in other places). What is going wrong with the bitmap part?
After a bit of research throughout some questions here (and I upvoted the ones that were especially useful), and in various coding places and quite a bit of late-night-self-coding-education, I have it working now. Below is the working code snippet: