Search code examples
androidandroid-imageviewandroid-image

capture image using front camera


I have a working code which is capturing a image using back camera and saving to sd card every thing is working but now I want to add a front camera which will capture the image instead of back camera

public class CameraExampleActivity extends Activity  {
Camera camera;
Preview preview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera_example);

    preview = new Preview(this);
    ((FrameLayout) findViewById(R.id.preview)).addView(preview);
}

public void click(View v) {
    preview.camera.takePicture(shutterCallback, null, jpegCallback);
}

ShutterCallback shutterCallback = new ShutterCallback() 
{
    public void onShutter() 
    {
        Log.d("Log", "Shuttered");
    }
};

PictureCallback jpegCallback = new PictureCallback() 
{
    public void onPictureTaken(byte[] imgData, Camera camera) 
    {
        //Compressing the image 640*480
        //-----------------------------------------
        Bitmap bmp=BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
        Bitmap resizedBmp = Bitmap.createScaledBitmap(bmp, 640, 480, false);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        resizedBmp.compress(CompressFormat.PNG, 0, bos);
        byte[] data = bos.toByteArray();
        //-----------------------------------------


        File pictureFileDir = getDir();

        if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

            Toast.makeText(CameraExampleActivity.this, "Can't create directory to save image.",Toast.LENGTH_LONG).show();
            return;
        }

        String photoFile = "MyPicture.jpg";
        String filename = pictureFileDir.getPath() + File.separator + photoFile;
        File pictureFile = new File(filename);

        try 
        {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
            Toast.makeText(CameraExampleActivity.this, "New Image saved:" + filename,Toast.LENGTH_LONG).show();
        }
        catch (Exception e) {
            Log.d("Error",""+e);
        }
    }
};

private File getDir() 
{
    File sdDir = Environment.getExternalStorageDirectory();
    return new File(sdDir, "Attendance Image");
}
}

Preview class

public class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";

SurfaceHolder mHolder;
public Camera camera;

Preview(Context context) {
    super(context);

    // Install a SurfaceHolder.Callback so we get notified when the
    // underlying surface is created and destroyed.
    mHolder = getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void surfaceCreated(SurfaceHolder holder) {
    // The Surface has been created, acquire the camera and tell it where
    // to draw.
    camera = Camera.open();
    try {
        camera.setPreviewDisplay(holder);

        camera.setPreviewCallback(new PreviewCallback() {

            public void onPreviewFrame(byte[] data, Camera arg1) {

                FileOutputStream outStream = null;
                try{
                    outStream = new FileOutputStream("/sdcard/Image.jpg");
                    outStream.write(data);
                    outStream.close();
                } catch (Throwable e){
                    Log.d("CAMERA", e.getMessage());
                } 

                Preview.this.invalidate();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
    // Surface will be destroyed when we return, so stop the preview.
    // Because the CameraDevice object is not a shared resource, it's very
    // important to release it when the activity is paused.
    camera.stopPreview();
    camera = null;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // Now that the size is known, set up the camera parameters and begin
    // the preview.
    Camera.Parameters parameters = camera.getParameters();
    parameters.setPreviewSize(w, h);
    camera.setParameters(parameters);
    camera.startPreview();
}

  }

Solution

  • Rather than use Camera.open(), you need to use the version of open() that takes the ID of the camera that you want. To find this ID, call getNumberOfCameras() on Camera, iterate over them, and find the one whose Camera.CameraInfo indicates that it is front-facing:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
      Camera.CameraInfo info=new Camera.CameraInfo();
    
      for (int i=0; i < Camera.getNumberOfCameras(); i++) {
        Camera.getCameraInfo(i, info);
    
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
          camera=Camera.open(i);
        }
      }
    }
    
    if (camera == null) {
      camera=Camera.open();
    }