private void TakePicture()
{
try
{
Activity activity = Activity;
if (activity == null || mCameraDevice == null) {
return;
}
CameraManager manager = (CameraManager) activity.GetSystemService(Context.CameraService);
// Pick the best JPEG size that can be captures with this CameraDevice
CameraCharacteristics characteristics = manager.GetCameraCharacteristics(mCameraDevice.Id);
Size[] jpegSizes = null;
if (characteristics != null)
{
jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
}
int width = 640;
int height = 480;
if (jpegSizes != null && jpegSizes.Length > 0)
{
width = jpegSizes[0].Width;
height = jpegSizes[0].Height;
}
// We use an ImageReader to get a JPEG from CameraDevice
// Here, we create a new ImageReader and prepare its Surface as an output from the camera
ImageReader reader = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
List<Surface> outputSurfaces = new List<Surface>(2);
outputSurfaces.Add(reader.Surface);
outputSurfaces.Add(new Surface(mTextureView.SurfaceTexture));
CaptureRequest.Builder captureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
captureBuilder.AddTarget(reader.Surface);
SetUpCaptureRequestBuilder(captureBuilder);
// Orientation
SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation;
captureBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(ORIENTATIONS.Get((int)rotation)));
// Output file
File file = new File(activity.GetExternalFilesDir(null), "pic.jpg");
// This listener is called when an image is ready in ImageReader
// Right click on ImageAvailableListener in your IDE and go to its definition
ImageAvailableListener readerListener = new ImageAvailableListener() { File = file };
// We create a Handler since we want to handle the resulting JPEG in a background thread
HandlerThread thread = new HandlerThread("CameraPicture");
thread.Start();
Handler backgroundHandler = new Handler(thread.Looper);
reader.SetOnImageAvailableListener(readerListener, backgroundHandler);
//This listener is called when the capture is completed
// Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above
// Right click on CameraCaptureListener in your IDE and go to its definition
CameraCaptureListener captureListener = new CameraCaptureListener() { Fragment = this, File = file };
mCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
{
OnConfiguredAction = (CameraCaptureSession session) => {
try
{
session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
}
catch (CameraAccessException ex)
{
Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
}
}
}, backgroundHandler );
}
catch (CameraAccessException ex) {
Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace);
}
}