processing camera frames as bitmaps at set intervals
I'm trying to do something very different with my android app: I need to
grab the image of the camera as a bitmap at timed intervals (every 2
seconds or so). I don't want it in real time because I need to run several
heavy processes on the bitmap once I have it, and for efficiency I don't
want to run those dozens of times a second. I also don't need to save it
as a file, I just need it in currentBitmap.
This is the code where I try to make it happen:
public class MainActivity extends Activity {
private Camera camera;
private CameraPreview camPreview;
private FrameLayout camLayout;
// The app will process the camera frame on intervals instead of constantly
private static final long PROCESS_TIME = 2000; //(in milliseconds)
private static final long START_TIME = 2000;
private Timer timer;
// I want the bitmap in this instance
private Bitmap currentBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
camLayout = (FrameLayout) findViewById(R.id.camera_preview);
setupCameraPreview();
// Set up the timer
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, START_TIME, PROCESS_TIME);
}
private void TimerMethod()
{ // Run Timer_Action on the same thread as the UI
this.runOnUiThread(Timer_Action);
}
private Runnable Timer_Action = new Runnable() {
public void run() {
// Process each bitmap here
try {
camera.takePicture(null, null, pictureCallback);
} catch (NullPointerException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
"Photo capture attempted",
Toast.LENGTH_SHORT).show();
}
};
private Camera.PictureCallback pictureCallback = new
Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
currentBitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
Toast.makeText(getApplicationContext(),
"Photo capture successful", Toast.LENGTH_SHORT).show();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
};
private void setupCameraPreview() {
try { // Try to initialize the camera
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
camPreview = new CameraPreview(this, camera);
camLayout.addView(camPreview);
} catch (Exception e) {
e.printStackTrace();
camera = null;
camPreview = null;
}
}
What happens when I run is that the camera preview and timer seem to run
fine. But the pictureCallback, data[], and currentBitmap all stay null, so
the try blocks throw their exceptions and the app moves on. My guess is
that pictureCallback isn't getting data from the camera, but how would I
fix that? and if that's not the problem than what is?
All help is very appreciated.
No comments:
Post a Comment