take Picture and save to a file - Android Media

Android examples for Media:Picture

Description

take Picture and save to a file

Demo Code

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;

public class Main {
  private static Camera camera;
  private static Camera.Parameters camParams;
  private static String fileName = "";
  /** Handles data for jpeg picture */
  private static PictureCallback jpegCallback = new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
      FileOutputStream outStream = null;
      try {/*from   w  w  w  . j a va2s. c  o m*/
        if (fileName.equals(""))
          outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",
              System.currentTimeMillis()));
        else
          outStream = new FileOutputStream(fileName);

        outStream.write(data);
        outStream.close();

      } catch (FileNotFoundException e) {
      } catch (IOException e) {
      } finally {

      }

    }
  };

  public static boolean takePicture(int cam, String name) {
    fileName = name;

    try {
      if (camera != null) {
        camera.release();
      }

      camera = Camera.open();

      camParams = camera.getParameters();

      camParams.set("camera-id", cam);
      camera.setParameters(camParams);

      camera.startPreview();
      camera.takePicture(null, null, jpegCallback);
      camera.stopPreview();

      camera.release();

      return true;
    } catch (Exception e) {
      return false;
    }
  }
}

Related Tutorials