Sunday 18 September 2011

Android: Taking pictures without a preview window

Why on earth one would want to take a picture with your Android phone without knowing what's going to be capture? Well, apps have their reasons, like the SOS app NoDistress.


Taking pictures programmatically is easy: do the same thing you'd do but set a dummy surface view to the camera.

Example

public void takePictureNoPreview(Context context){
  // open back facing camera by default
  Camera myCamera=Camera.open();

  if(myCamera!=null){
    try{
      //set camera parameters if you want to
      //...

      // here, the unused surface view and holder
      SurfaceView dummy=new SurfaceView(context)
      myCamera.setPreviewDisplay(dummy.getHolder());    
      myCamera.startPreview(); 
      
      myCamera.takePicture(null, null, getJpegCallback()):
      
    }finally{
      myCamera.close();
    }      

  }else{
    //booo, failed!
  }


  private PictureCallback getJpegCallback(){
    PictureCallback jpeg=new PictureCallback() {   
      @Override
      public void onPictureTaken(byte[] data, Camera camera) {
        FileOutputStream fos;
        try {
          fos = new FileOutputStream("test.jpeg");
          fos.write(data);
          fos.close();
        }  catch (IOException e) {
          //do something about it
        }
      }
    };
  }
}


---
Programming tricks and tips for android developers