// Sets up member variables related to camera. private void SetUpCameraOutputs(int width, int height) { CameraManager manager = (CameraManager)Activity.GetSystemService(Context.CameraService); try { foreach (string cameraId in manager.GetCameraIdList()) { CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); Integer facing = (Integer)characteristics.Get(CameraCharacteristics.LensFacing); if (facing != null && facing == (Integer.ValueOf((int)LensFacing.Front))) { continue; } StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); if (map == null) { continue; } // For still image captures, we use the largest available size. Size largest = (Size)Collections.Max(Arrays.AsList(map.GetOutputSizes((int)ImageFormatType.Jpeg)), new CompareSizesByArea()); _imageReader = ImageReader.NewInstance(largest.Width, largest.Height, ImageFormatType.Jpeg, 2); _imageReader.SetOnImageAvailableListener(OnImageAvailableListener, BackgroundHandler); _sensorOrientation = (int)characteristics.Get(CameraCharacteristics.SensorOrientation); bool swapped = IsCameraRoationSameAsDevice(Activity.WindowManager.DefaultDisplay.Rotation, _sensorOrientation); Size rotatedSize = GetRotatedPreviewSize(width, height, swapped); Size maxSize = GetMaxPrieviewSize(width, height, swapped); // Danger, W.R.! Attempting to use too large a preview size could exceed the camera // bus' bandwidth limitation, resulting in gorgeous previews but the storage of // garbage capture data. _previewSize = ChooseOptimalSize(map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture))), rotatedSize.Width, rotatedSize.Height, maxSize.Width, maxSize.Height, largest); SetTextureViewAspectRatio(); // Check if the flash is supported. Boolean available = (Boolean)characteristics.Get(CameraCharacteristics.FlashInfoAvailable); _flashSupported = (available == null ? false : (bool)available); _cameraId = cameraId; return; } } catch (CameraAccessException e) { e.PrintStackTrace(); } catch//camera_error { ErrorDialog.NewInstance(GetString(Resource.String.camera_error)).Show(ChildFragmentManager, FRAGMENT_DIALOG); } }
//Tries to open a CameraDevice public void OpenCamera(int width, int height) { if (null == Activity || Activity.IsFinishing) { return; } CameraManager manager = (CameraManager)Activity.GetSystemService(Context.CameraService); try { if (!CameraOpenCloseLock.TryAcquire(2500, TimeUnit.Milliseconds)) { throw new RuntimeException("Time out waiting to lock camera opening."); } string cameraId = manager.GetCameraIdList()[0]; CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); videoSize = ChooseVideoSize(map.GetOutputSizes(Class.FromType(typeof(MediaRecorder)))); previewSize = ChooseOptimalSize(map.GetOutputSizes(Class.FromType(typeof(MediaRecorder))), width, height, videoSize); int orientation = (int)Resources.Configuration.Orientation; if (orientation == (int)global::Android.Content.Res.Orientation.Landscape) { TextureView.SetAspectRatio(previewSize.Width, previewSize.Height); } else { TextureView.SetAspectRatio(previewSize.Height, previewSize.Width); } ConfigureTransform(width, height); MediaRecorder = new MediaRecorder(); manager.OpenCamera(cameraId, stateListener, null); } catch (CameraAccessException) { Toast.MakeText(Activity, "Cannot access the camera.", ToastLength.Short).Show(); Activity.Finish(); } catch (NullPointerException) { var dialog = new ErrorDialog(); dialog.Show(FragmentManager, "dialog"); } catch (InterruptedException) { throw new RuntimeException("Interrupted while trying to lock camera opening."); } }
//Tries to open a CameraDevice public void openCamera() { if (null == Activity || Activity.IsFinishing || opening_camera) { return; } opening_camera = true; CameraManager manager = (CameraManager)Activity.GetSystemService(Context.CameraService); try { string camera_id = manager.GetCameraIdList()[0]; CameraCharacteristics characteristics = manager.GetCameraCharacteristics(camera_id); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); preview_size = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0]; int orientation = (int)Resources.Configuration.Orientation; if (orientation == (int)Android.Content.Res.Orientation.Landscape) { texture_view.SetAspectRatio(preview_size.Width, preview_size.Height); } else { texture_view.SetAspectRatio(preview_size.Height, preview_size.Width); } manager.OpenCamera(camera_id, state_listener, null); } catch (CameraAccessException) { Toast.MakeText(Activity, "Cannot access the camera.", ToastLength.Short).Show(); Activity.Finish(); } catch (NullPointerException) { var dialog = new ErrorDialog(); dialog.Show(FragmentManager, "dialog"); } }
private void Initialize() { CameraManager manager = (CameraManager)m_Context.GetSystemService(Context.CameraService); String backCameraId; foreach (String cameraId in manager.GetCameraIdList()) { CameraCharacteristics chars = manager.GetCameraCharacteristics(cameraId); //if (chars.Get(CameraCharacteristics.LensFacing) == CameraCharacteristics.Key.LensFacing.) { backCameraId = cameraId; StreamConfigurationMap configs = (StreamConfigurationMap)manager.GetCameraCharacteristics(cameraId).Get(CameraCharacteristics.ScalerStreamConfigurationMap); Android.Util.Size[] size = configs.GetOutputSizes((int)Android.Graphics.ImageFormatType.Jpeg); //ここに含まれるSizeを指定する ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams)m_surfaceView.LayoutParameters; lp.Width = 320; //横幅 lp.Height = 240; //縦幅 m_surfaceView.LayoutParameters = lp; m_surfaceView.Holder.SetFixedSize(240, 320);//縦で持つときはwidth height が逆 manager.OpenCamera(backCameraId, new OpenCameraCallback(this), null); break; } }
/// <summary> /// Opens the camera. /// </summary> public void OpenCamera() { if (_context == null || OpeningCamera) { return; } OpeningCamera = true; _manager = (CameraManager)_context.GetSystemService(Context.CameraService); try { string cameraId = _manager.GetCameraIdList()[0]; // To get a list of available sizes of camera preview, we retrieve an instance of // StreamConfigurationMap from CameraCharacteristics CameraCharacteristics characteristics = _manager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); _previewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0]; Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation; if (orientation == Android.Content.Res.Orientation.Landscape) { _cameraTexture.SetAspectRatio(_previewSize.Width, _previewSize.Height); } else { _cameraTexture.SetAspectRatio(_previewSize.Height, _previewSize.Width); } HandlerThread thread = new HandlerThread("CameraPreview"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); // We are opening the camera with a listener. When it is ready, OnOpened of mStateListener is called. _manager.OpenCamera(cameraId, _stateListener, null); } catch (Java.Lang.Exception error) { _log.WriteLineTime(_tag + "\n" + "OpenCamera() Failed to open camera \n " + "ErrorMessage: \n" + error.Message + "\n" + "Stacktrace: \n " + error.StackTrace); Available?.Invoke(this, false); } catch (System.Exception error) { _log.WriteLineTime(_tag + "\n" + "OpenCamera() Failed to open camera \n " + "ErrorMessage: \n" + error.Message + "\n" + "Stacktrace: \n " + error.StackTrace); Available?.Invoke(this, false); } }
/// <summary> /// プレビューの画面サイズを算出 /// </summary> /// <param name="cameraId"></param> /// <returns></returns> private Android.Util.Size GetPreviewSize(string cameraId) { CameraManager manager = (CameraManager)activity.GetSystemService(Context.CameraService); var characteristics = manager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); // 最大サイズからratioを取得 var maxSize = (Android.Util.Size)Collections.Max(Arrays.AsList(map.GetOutputSizes((int)ImageFormatType.Jpeg)), new CompareSizesByArea()); int h = maxSize.Height; int w = maxSize.Width; System.Diagnostics.Debug.WriteLine($"max size: width={w},height={h}"); // ディスプレイサイズ var displaySize = new Android.Graphics.Point(); activity.WindowManager.DefaultDisplay.GetSize(displaySize); // 横向きに補正 var maxWidth = displaySize.X > displaySize.Y ? displaySize.X : displaySize.Y; var maxHeight = displaySize.Y < displaySize.X ? displaySize.Y : displaySize.X; System.Diagnostics.Debug.WriteLine($"display: width={maxWidth},height={maxHeight}"); // 画面サイズに収まり、アスペクト比が一致するサイズ var list = new List <Android.Util.Size>(); var sizes = map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture))); foreach (var size in sizes) { System.Diagnostics.Debug.WriteLine($"size: width={size.Width},height={size.Height}"); if ((size.Width <= maxWidth) && (size.Height <= maxHeight) && size.Height == size.Width * h / w) { list.Add(size); } } // 最大のやつを取得 var prevSize = (Android.Util.Size)Collections.Max(list, new CompareSizesByArea()); // 無理から縦向きに変更 var ret = new Android.Util.Size(prevSize.Height, prevSize.Width); return(ret); }
void GetFrontSizes() { CameraManager manager = (CameraManager)Context.GetSystemService(Context.CameraService); CameraCharacteristics characteristics = manager.GetCameraCharacteristics(frontCameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); frontCameraSizes = map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture))); }
public void configureStream() { CameraCharacteristics characteristics = _cameraManager.GetCameraCharacteristics(_id); StreamConfigurationMap configs = (StreamConfigurationMap)(characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)); sa = configs.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture))); //sa = configs.GetOutputSizes((int)ImageFormatType.Nv16); for (int i = 0; i < sa.Length; i++) { System.Diagnostics.Debug.WriteLine("width : " + sa[i].Width + " Height : " + sa[i].Height + "\n"); } }
protected override void FindLargestResolution() { StreamConfigurationMap map = (StreamConfigurationMap)CameraCharacteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); DroidSize[] imageSupportedSizesAndroid = map.GetOutputSizes((int)ImageFormatType.Jpeg); DroidSize largestSizeAndroid = imageSupportedSizesAndroid .OrderByDescending(droidSize => (long)droidSize.Height * droidSize.Width) .FirstOrDefault(); _largestImageResolution = new Size(largestSizeAndroid.Width, largestSizeAndroid.Height); }
/// <summary> /// /// </summary> /// <param name="width">Device screen width, in pixels.</param> /// <param name="height">Device screen height, in pixels.</param> public void SetupCamera(int width, int height) { CameraManager cameraManager = (CameraManager)mActivity.GetSystemService(Context.CameraService); try { SurfaceTexture SurfaceTextureClassIntance = new SurfaceTexture(true); foreach (string id in cameraManager.GetCameraIdList()) { CameraCharacteristics characteristics = cameraManager.GetCameraCharacteristics(id); int cameraLensFacing = (int)characteristics.Get(CameraCharacteristics.LensFacing); if (cameraLensFacing == null) { continue; } if (cameraLensFacing != (int)LensFacing.Front) { continue; } StreamConfigurationMap maps = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); if (maps == null || maps.GetOutputSizes(SurfaceTextureClassIntance.Class) == null) { continue; } mPreviewSize = getOptimalSize(maps.GetOutputSizes(SurfaceTextureClassIntance.Class), width, height); mCameraId = id; Log.Debug(TAG, "Preview width = " + mPreviewSize.Width + ", height = " + mPreviewSize.Height + ", cameraId = " + mCameraId); break; } } catch (CameraAccessException e) { Log.Debug(TAG, "Set upCamera error"); } }
public List <CameraPixels> GetCameraResolution() { List <CameraPixels> camPixels = new List <CameraPixels>(); if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) { //Lolipop and above CameraManager camMan = (CameraManager)mactivity.GetSystemService(Context.CameraService); string[] camId = camMan.GetCameraIdList(); CameraCharacteristics camChar = camMan.GetCameraCharacteristics(camId[0]); //0 - mostly for back cam StreamConfigurationMap camMap = (StreamConfigurationMap)camChar.Get(CameraCharacteristics.ScalerStreamConfigurationMap); Android.Util.Size[] sizes = camMap.GetOutputSizes((int)ImageFormatType.Jpeg); System.Diagnostics.Debug.WriteLine($"Camera sizes: {sizes.Length}"); foreach (var size in sizes) { //System.Diagnostics.Debug.WriteLine($"Sizes: {size.Width} x {size.Height} = {Convert.ToDouble(size.Width) * Convert.ToDouble(size.Height) / Convert.ToDouble(1024000)} megs"); camPixels.Add(new CameraPixels() { Height = size.Height, Width = size.Width, Megapixels = Math.Round(Convert.ToDecimal(size.Width) * Convert.ToDecimal(size.Height) / Convert.ToDecimal(1000000), 1) }); } } else { //pre-lolipop Android.Hardware.Camera cam = Android.Hardware.Camera.Open(); Android.Hardware.Camera.Parameters camParam = cam.GetParameters(); IList <Android.Hardware.Camera.Size> plSizes = camParam.SupportedPictureSizes; foreach (var size in plSizes) { System.Diagnostics.Debug.WriteLine($"Sizes: {size.Width} x {size.Height} = {Convert.ToDouble(size.Width) * Convert.ToDouble(size.Height) / Convert.ToDouble(1024000)} megs"); camPixels.Add(new CameraPixels() { Height = size.Height, Width = size.Width, Megapixels = Math.Round(Convert.ToDecimal(size.Width) * Convert.ToDecimal(size.Height) / Convert.ToDecimal(1000000), 1) }); } cam.Release(); } return(camPixels); }
public void OpenCamera(bool IsSwitchCam) { cameraManager = (CameraManager)GetSystemService(Context.CameraService); try { SyncCameraPosition(IsSwitchCam); string cameraId = cameraManager.GetCameraIdList()[CurrentCameraIndex]; CameraCharacteristics characteristics = cameraManager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); previewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0]; Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation; if (orientation == Android.Content.Res.Orientation.Landscape) { autoFitTextureView.SetAspectRatio(previewSize.Width, previewSize.Height); } else { autoFitTextureView.SetAspectRatio(previewSize.Height, previewSize.Width); } HandlerThread thread = new HandlerThread("CameraPreview"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); cameraManager.OpenCamera(cameraId, cameraStateListener, null); var available = (bool)characteristics.Get(CameraCharacteristics.FlashInfoAvailable); if (available) { FlashSupported = true; } else { FlashSupported = false; } } catch (Java.Lang.Exception error) { ShowToastMessage("Failed to open camera"); DebugMessage("ErrorMessage: \n" + error.Message + "\n" + "Stacktrace: \n " + error.StackTrace); } catch (System.Exception error) { ShowToastMessage("Failed to open camera"); DebugMessage("ErrorMessage: \n" + error.Message + "\n" + "Stacktrace: \n " + error.StackTrace); } }
public static void dumpFormatInfo(Context context) { CameraManager manager = ((CameraManager)(context.GetSystemService(Context.CameraService))); string[] camIds = new string[0]; try { camIds = manager.GetCameraIdList(); } catch (CameraAccessException e) { Log.Debug(TAG, "Cam access exception getting IDs"); } if ((camIds.Length < 1)) { Log.Debug(TAG, "No cameras found"); } string id = camIds[0]; Log.Debug(TAG, ("Using camera id " + id)); try { CameraCharacteristics characteristics = manager.GetCameraCharacteristics(id); StreamConfigurationMap configs = (Android.Hardware.Camera2.Params.StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); //CameraCharacteristics.ScalerStreamConfigurationMap); foreach (int format in configs.GetOutputFormats()) { Log.Debug(TAG, ("Getting sizes for format: " + format)); foreach (Size s in configs.GetOutputSizes(format)) { Log.Debug(TAG, ("\t" + s.ToString())); } } int[] effects = (int[])characteristics.Get(CameraCharacteristics.ControlAvailableEffects); foreach (int effect in effects) { Log.Debug(TAG, ("Effect available: " + effect)); } } catch (CameraAccessException e) { Log.Debug(TAG, "Cam access exception getting characteristics."); } }
/* * Helpful debugging method: Dump all supported camera formats to log. You don't need to run * this for normal operation, but it's very helpful when porting this code to different * hardware. */ public static void DumpFormatInfo(Context context) { // Discover the camera instance CameraManager manager = (CameraManager)context.GetSystemService(Context.CameraService); string[] camIds = null; try { camIds = manager.GetCameraIdList(); } catch (CameraAccessException e) { Log.Warn(TAG, "Cannot get the list of available cameras", e); } if (camIds == null || camIds.Length < 1) { Log.Debug(TAG, "No cameras found"); return; } Log.Debug(TAG, "Using camera id " + camIds[0]); try { CameraCharacteristics characteristics = manager.GetCameraCharacteristics(camIds[0]); StreamConfigurationMap configs = (StreamConfigurationMap)characteristics.Get( CameraCharacteristics.ScalerStreamConfigurationMap); foreach (var format in configs.GetOutputFormats()) { Log.Debug(TAG, "Getting sizes for format: " + format); foreach (var s in configs.GetOutputSizes(format)) { Log.Debug(TAG, "\t" + s.ToString()); } } int[] effects = (int[])characteristics.Get(CameraCharacteristics.ControlAvailableEffects); foreach (var effect in effects) { Log.Debug(TAG, "Effect available: " + effect); } } catch (CameraAccessException) { Log.Debug(TAG, "Cam access exception getting characteristics."); } }
private void OpenCamera() { CameraManager manager = (CameraManager)GetSystemService(Context.CameraService); String CameraId = manager.GetCameraIdList()[0]; CameraCharacteristics cameraCharacteristics = manager.GetCameraCharacteristics(CameraId); StreamConfigurationMap map = (StreamConfigurationMap) cameraCharacteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); statecallback.imagedimension = map.GetOutputSizes(256)[0]; manager.OpenCamera("0", statecallback, Handler); // Toast.MakeText(this, "ok", ToastLength.Long).Show(); //throw new NotImplementedException(); }
// Opens a CameraDevice. The result is listened to by 'mStateListener'. private void OpenCamera() { Activity activity = Activity; if (activity == null || activity.IsFinishing || mOpeningCamera) { return; } mOpeningCamera = true; CameraManager manager = (CameraManager)activity.GetSystemService(Context.CameraService); try { string cameraId = manager.GetCameraIdList()[0]; // To get a list of available sizes of camera preview, we retrieve an instance of // StreamConfigurationMap from CameraCharacteristics CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); mPreviewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0]; Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation; if (orientation == Android.Content.Res.Orientation.Landscape) { mTextureView.SetAspectRatio(mPreviewSize.Width, mPreviewSize.Height); } else { mTextureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width); } // We are opening the camera with a listener. When it is ready, OnOpened of mStateListener is called. manager.OpenCamera(cameraId, mStateListener, null); } catch (CameraAccessException ex) { Toast.MakeText(activity, "Cannot access the camera.", ToastLength.Short).Show(); Activity.Finish(); } catch (NullPointerException) { var dialog = new ErrorDialog(); dialog.Show(FragmentManager, "dialog"); } }
/// <summary> /// Open the camera. Camera API used depends on the device's sdk version num /// </summary> /// <param name="cameraIndex"></param> private void OpenCamera(int cameraIndex = 0) { Activity activity = Activity; if (activity == null || activity.IsFinishing || mOpeningCamera) { return; } mOpeningCamera = true; try { // Camera2 API is only supported after Lollipop, but newer devices may not support Camera1 if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) { CameraManager manager = (CameraManager)activity.GetSystemService(Android.Content.Context.CameraService); string[] idList = manager.GetCameraIdList(); string cameraId = idList[cameraIndex]; switchCameraButton.Enabled = idList.Length > 1; switchCameraButton.Visibility = idList.Length > 1 ? ViewStates.Visible : ViewStates.Gone; // The onion skin has to be repositioned for the front facing camera if (cameraIndex == 1) { previousPhoto.SetScaleType(ImageView.ScaleType.FitStart); } else { previousPhoto.SetScaleType(ImageView.ScaleType.CenterCrop); } CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); mPreviewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0]; Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation; textureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width); manager.OpenCamera(cameraId, mStateListener, null); } else { camera = Android.Hardware.Camera.Open(cameraIndex); camEnabled = true; textureView1.LayoutParameters = new FrameLayout.LayoutParams(width, height, GravityFlags.Center); if (cameraType == CameraFacing.Back) { previousPhoto.LayoutParameters = new FrameLayout.LayoutParams(width, height, GravityFlags.Fill); } else { previousPhoto.LayoutParameters = new FrameLayout.LayoutParams(width, height, GravityFlags.Top); } surfaceTexture = surface; camera.SetPreviewTexture(surface); takePhotoButton.Enabled = true; switchCameraButton.Enabled = true; switchCameraButton.Visibility = ViewStates.Visible; PrepareAndStartCamera1(); } } catch (CameraAccessException ex) { Toast.MakeText(activity, AppResources.Camera_noAccess, ToastLength.Short).Show(); Activity.Finish(); } }
//Tries to open a CameraDevice public void openCamera(int width, int height, Bundle savedInstanceState) { if (null == Activity || Activity.IsFinishing) { return; } manager = (CameraManager)Activity.GetSystemService(Context.CameraService); try { if (!cameraOpenCloseLock.TryAcquire(2500, TimeUnit.Milliseconds)) { throw new RuntimeException("Time out waiting to lock camera opening."); } string cameraId = GetCam(manager, CURRENTCAMERA); CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); videoSize = ChooseVideoSize(map.GetOutputSizes(Class.FromType(typeof(MediaRecorder)))); previewSize = ChooseOptimalSize(map.GetOutputSizes(Class.FromType(typeof(MediaRecorder))), width, height, videoSize); int orientation = (int)Resources.Configuration.Orientation; if (orientation == (int)Android.Content.Res.Orientation.Landscape) { textureView.SetAspectRatio(previewSize.Width, previewSize.Height); } else { textureView.SetAspectRatio(previewSize.Height, previewSize.Width); } configureTransform(width, height); mediaRecorder = new MediaRecorder(); if (stateListener == null) { stateListener = new MyCameraStateCallback(this); } manager.OpenCamera(cameraId, stateListener, null); SetupComplete?.Invoke(); max = (Rect)characteristics.Get(CameraCharacteristics.SensorInfoActiveArraySize); size = (Size)characteristics.Get(CameraCharacteristics.SensorInfoPixelArraySize); controls = new Camera2Controls(cameraDevice, size, max); controls.OnFocus += DoFocus; try { ChildFragmentManager.BeginTransaction().Replace(Resource.Id.camera_controls, controls).Commit(); } catch (System.Exception) { } } catch (CameraAccessException) { Toast.MakeText(Activity, "Cannot access the camera.", ToastLength.Short).Show(); Activity.Finish(); } catch (NullPointerException) { //var dialog = new ErrorDialog(); //dialog.Show(ChildFragmentManager, "dialog"); } catch (InterruptedException) { throw new RuntimeException("Interrupted while trying to lock camera opening."); } }
// Opens a CameraDevice. The result is listened to by 'mStateListener'. private void OpenCamera() { Activity activity = Activity; if (activity == null || activity.IsFinishing || mOpeningCamera) { return; } mOpeningCamera = true; CameraManager manager = (CameraManager)activity.GetSystemService(Context.CameraService); try { bool front = Arguments.GetBoolean(EXTRA_USE_FRONT_FACING_CAMERA); if (front) { Log.Debug("VoiceCamera", "Front specified"); } else { Log.Debug("VoiceCamera", "Back Specified"); } Log.Debug("VoiceCamera", "Front ID: " + (int)LensFacing.Front + " Back ID: " + (int)LensFacing.Back); foreach (var cameraId in manager.GetCameraIdList()) { // To get a list of available sizes of camera preview, we retrieve an instance of // StreamConfigurationMap from CameraCharacteristics var characteristics = manager.GetCameraCharacteristics(cameraId); var lens = characteristics.Get(CameraCharacteristics.LensFacing); Log.Debug("VoiceCamera", "LensFacing: " + lens.ToString()); if (!IsCameraSpecified) { Log.Debug("VoiceCamera", "camera not specified"); if ((int)lens == (int)LensFacing.Front) { Log.Debug("VoiceCamera", "Skip front facing camera"); //we don't use a front facing camera in this sample. continue; } } else if (!ShouldUseCamera((int)lens)) { Log.Debug("VoiceCamera", "Skipping over camera, should not use"); //TODO: Handle case where there is no camera match continue; } Log.Debug("VoiceCamera", "Using this camera"); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); mPreviewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0]; Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation; if (orientation == Android.Content.Res.Orientation.Landscape) { mTextureView.SetAspectRatio(mPreviewSize.Width, mPreviewSize.Height); } else { mTextureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width); } // We are opening the camera with a listener. When it is ready, OnOpened of mStateListener is called. manager.OpenCamera(cameraId, mStateListener, null); return; } } catch (CameraAccessException ex) { Toast.MakeText(activity, "Cannot access the camera.", ToastLength.Short).Show(); Activity.Finish(); } catch (NullPointerException) { var dialog = new ErrorDialog(); dialog.Show(FragmentManager, "dialog"); } }
public static int StartCapture(SurfaceTexture previewSurfaceTexture, Size previewSize) { // Find the optimal camera and size string optimalCamId = null; string[] availableCameras = _cameraManager.GetCameraIdList(); for (int i = 0; i < availableCameras.Length; i++) { CameraCharacteristics characteristics = _cameraManager.GetCameraCharacteristics(availableCameras[i]); var camFace = (Java.Lang.Integer)characteristics.Get(CameraCharacteristics.LensFacing); if (camFace != null && camFace.IntValue() == (int)LensFacing.Back) { optimalCamId = availableCameras[i]; StreamConfigurationMap streamConfig = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); List <Size> availableSizes = new List <Size>(streamConfig.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))); if (availableSizes.Exists(s => s.Width == previewSize.Width && s.Height == previewSize.Height)) { previewSurfaceTexture.SetDefaultBufferSize(previewSize.Width, previewSize.Height); break; } availableSizes.Sort((s1, s2) => s1.Width * s1.Height - s2.Width * s2.Height); Size maxSize = availableSizes[availableSizes.Count - 1]; availableSizes.RemoveAll(s => (s.Height != s.Width * maxSize.Height / maxSize.Width)); availableSizes.Add(previewSize); availableSizes.Sort((s1, s2) => s1.Width * s1.Height - s2.Width * s2.Height); int previewSizeIndex = availableSizes.IndexOf(previewSize); if (previewSizeIndex < availableSizes.Count - 1) { previewSurfaceTexture.SetDefaultBufferSize(availableSizes[previewSizeIndex + 1].Width, availableSizes[previewSizeIndex + 1].Height); } else { previewSurfaceTexture.SetDefaultBufferSize(availableSizes[previewSizeIndex - 1].Width, availableSizes[previewSizeIndex - 1].Height); } break; } } if (optimalCamId == null) { return(1); } // Open the camera // We use the semaphore to wait for the 'onOpen' function to be called, so that we can aquire the camera device. Semaphore utilSemaphore = new Semaphore(0, 1); void onOpen(CameraDevice camera) { _camera = camera; utilSemaphore.Release(); } void onDisconnected(CameraDevice camera) { camera.Close(); _camera = null; } void onError(CameraDevice camera, CameraError error) { onDisconnected(camera); } _backgroundThread = new HandlerThread("CameraBackgroundWorker"); _backgroundThread.Start(); _backgroundHandler = new Handler(_backgroundThread.Looper); _cameraManager.OpenCamera(optimalCamId, new FunctionalCameraStateListener(onOpen, onDisconnected, onError), _backgroundHandler); utilSemaphore.WaitOne(); if (_camera == null) { return(2); } // Start the capture session bool configureFailed = false; Surface previewSurface = new Surface(previewSurfaceTexture); void onConfigured(CameraCaptureSession session) { _captureSession = session; var captureRequestBuilder = _camera.CreateCaptureRequest(CameraTemplate.Preview); captureRequestBuilder.AddTarget(previewSurface); captureRequestBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousVideo); var captureRequest = captureRequestBuilder.Build(); _captureSession.SetRepeatingRequest(captureRequest, null, _backgroundHandler); utilSemaphore.Release(); } void onConfigureFailed(CameraCaptureSession session) { configureFailed = true; session.Close(); utilSemaphore.Release(); } _camera.CreateCaptureSession(new Surface[] { previewSurface }, new FunctionalCameraCaptureSessionListener(onConfigured, onConfigureFailed), _backgroundHandler); utilSemaphore.WaitOne(); if (configureFailed) { onDisconnected(_camera); return(3); } return(0); }
// Opens a CameraDevice. The result is listened to by 'cameraStateListener'. private void OpenCamera() { var activity = this.Activity; if (activity == null || activity.IsFinishing) { return; } this.tracer.Debug("OpenCamera"); this.tracer.Debug("OpenCamera: this.facing={0}", this.facing.ToString()); var cameraManager = (CameraManager)activity.GetSystemService(Context.CameraService); try { if (!this.mCameraOpenCloseLock.TryAcquire(2500, TimeUnit.Milliseconds)) { const string ErrorMessage = "Time out waiting to lock camera opening."; this.tracer.Error(ErrorMessage); throw new RuntimeException(ErrorMessage); } string idForOpen = null; string[] camerasIds = cameraManager.GetCameraIdList(); foreach (string id in camerasIds) { CameraCharacteristics cameraCharacteristics = cameraManager.GetCameraCharacteristics(id); var cameraLensFacing = (Integer)cameraCharacteristics.Get(CameraCharacteristics.LensFacing); CameraFacingDirection cameraFacingDirection = ToCameraFacingDirection(cameraLensFacing); CameraFacingDirection configuredFacingDirection = ToCameraFacingDirection(this.facing); this.tracer.Debug("OpenCamera: cameraFacingDirection={0}, configuredFacingDirection={1}", cameraFacingDirection, configuredFacingDirection); if (cameraFacingDirection == configuredFacingDirection) { idForOpen = id; break; } } var cameraId = idForOpen ?? camerasIds[0]; this.tracer.Debug("OpenCamera: idForOpen={0}", idForOpen); this.tracer.Debug("OpenCamera: idForOpen={0}", idForOpen); this.tracer.Debug("OpenCamera: cameraId={0}", cameraId); // To get a list of available sizes of camera preview, we retrieve an instance of // StreamConfigurationMap from CameraCharacteristics CameraCharacteristics characteristics = cameraManager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); this.previewSize = map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture)))[0]; // We assume that the top-most element is the one with the best resolution Orientation orientation = this.Resources.Configuration.Orientation; if (orientation == Orientation.Landscape) { this.autoFitTextureView.SetAspectRatio(this.previewSize.Width, this.previewSize.Height); } else { this.autoFitTextureView.SetAspectRatio(this.previewSize.Height, this.previewSize.Width); } ////this.ConfigureTransform(this.autoFitTextureView.Width, this.autoFitTextureView.Width); // We are opening the camera with a listener. When it is ready, OnOpened of cameraStateListener is called. cameraManager.OpenCamera(cameraId, this.cameraStateListener, null); } catch (CameraAccessException caex) { this.tracer.Exception(caex, "Cannot access the camera."); Toast.MakeText(activity, "Cannot access the camera.", ToastLength.Short).Show(); this.Activity.Finish(); } catch (NullPointerException npex) { this.tracer.Exception(npex, "This device doesn't support Camera2 API."); var dialog = new ErrorDialog(); dialog.Show(this.FragmentManager, "dialog"); } catch (InterruptedException e) { const string ErrorMessage = "Interrupted while trying to lock camera opening."; this.tracer.Exception(e, ErrorMessage); throw new RuntimeException(ErrorMessage); } catch (Exception ex) { this.tracer.Exception(ex); throw; } }
/** * Sets up member variables related to camera. * * @param width The width of available size for camera preview * @param height The height of available size for camera preview */ private void setUpCameraOutputs(int width, int height) { Activity activity = Activity; CameraManager manager = (CameraManager)activity.GetSystemService(Android.Content.Context.CameraService); try { foreach (String cameraId in manager.GetCameraIdList()) { CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); // We don't use a front facing camera in this sample. var facing = (Java.Lang.Integer)characteristics.Get(CameraCharacteristics.LensFacing); if (facing != null && facing.IntValue() == (int)LensFacing.Front) { continue; } StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); if (map == null) { continue; } // // For still image captures, we use the largest available size. Size largest = (Size)Collections.Max( Arrays.AsList(map.GetOutputSizes((int)ImageFormat.Jpeg)), new CompareSizesByArea()); imageReader = ImageReader.NewInstance( largest.Width, largest.Height, ImageFormat.Jpeg, /*maxImages*/ 2); // Find out if we need to swap dimension to get the preview size relative to sensor // coordinate. var displayRotation = activity.WindowManager.DefaultDisplay.Rotation; // getDefaultDisplay().getRotation(); // noinspection ConstantConditions /* Orientation of the camera sensor */ var sensorOrientation = (int)characteristics.Get(CameraCharacteristics.SensorOrientation); bool swappedDimensions = false; switch (displayRotation) { case SurfaceOrientation.Rotation0: // Surface.ROTATION_0: case SurfaceOrientation.Rotation180: if (sensorOrientation == 90 || sensorOrientation == 270) { swappedDimensions = true; } break; case SurfaceOrientation.Rotation90: case SurfaceOrientation.Rotation270: if (sensorOrientation == 0 || sensorOrientation == 180) { swappedDimensions = true; } break; default: Log.Error(TAG, "Display rotation is invalid: " + displayRotation); break; } Point displaySize = new Point(); activity.WindowManager.DefaultDisplay.GetSize(displaySize); int rotatedPreviewWidth = width; int rotatedPreviewHeight = height; int maxPreviewWidth = displaySize.X; int maxPreviewHeight = displaySize.Y; if (swappedDimensions) { rotatedPreviewWidth = height; rotatedPreviewHeight = width; maxPreviewWidth = displaySize.Y; maxPreviewHeight = displaySize.X; } if (maxPreviewWidth > MAX_PREVIEW_WIDTH) { maxPreviewWidth = MAX_PREVIEW_WIDTH; } if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) { maxPreviewHeight = MAX_PREVIEW_HEIGHT; } previewSize = chooseOptimalSize( map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture))), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest); // We fit the aspect ratio of TextureView to the size of preview we picked. var orientation = Resources.Configuration.Orientation; if (orientation == Android.Content.Res.Orientation.Landscape) { textureView.setAspectRatio(previewSize.Width, previewSize.Height); } else { textureView.setAspectRatio(previewSize.Height, previewSize.Width); } this.cameraId = cameraId; return; } } catch (CameraAccessException e) { Log.Error(TAG, "Failed to access Camera", e); } catch (Java.Lang.NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. // ErrorDialog.newInstance(getString(R.string.camera_error)) // .show(getChildFragmentManager(), FRAGMENT_DIALOG); } }
/// <summary> /// Sets up state related to camera that is needed before opening a {@link CameraDevice}. /// </summary> /// <returns><c>true</c>, if up camera outputs was set, <c>false</c> otherwise.</returns> bool SetUpCameraOutputs() { var activity = this; CameraManager manager = (CameraManager)activity.GetSystemService(Context.CameraService); if (manager == null) { Log.Error(TAG, "This device doesn't support Camera2 API."); return(false); } try { // Find a CameraDevice that supports YUV captures, and configure state. foreach (string cameraId in manager.GetCameraIdList()) { CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); /* * // We only use a camera that supports YUV in this sample. * if (!Contains(characteristics.Get( * CameraCharacteristics.RequestAvailableCapabilities).ToArray<int>(), * (int)RequestAvailableCapabilities.YuvReprocessing)) * { * continue; * }*/ StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get( CameraCharacteristics.ScalerStreamConfigurationMap); // For still image captures, we use the largest available size. Android.Util.Size[] yuvs = map.GetOutputSizes((int)ImageFormatType.Yuv420888); Android.Util.Size largestYuv = yuvs.OrderByDescending(element => element.Width * element.Height).Last(); lock (mCameraStateLock) { // Set up ImageReaders for JPEG and RAW outputs. Place these in a reference // counted wrapper to ensure they are only closed when all background tasks // using them are finished. if (mYuvImageReader == null || mYuvImageReader.GetAndRetain() == null) { mYuvImageReader = new RefCountedAutoCloseable <ImageReader>( ImageReader.NewInstance(largestYuv.Width, largestYuv.Height, ImageFormatType.Yuv420888, /*maxImages*/ 5)); } mYuvImageReader.Get().SetOnImageAvailableListener( mOnYuvImageAvailableListener, mBackgroundHandler); mCharacteristics = characteristics; mCameraId = cameraId; } return(true); } } catch (CameraAccessException e) { e.PrintStackTrace(); } // If we found no suitable cameras for capturing YUV, warn the user. Log.Error(TAG, "This device doesn't support capturing YUV photos"); return(false); }
public Task <byte[]> TakePicture() { if (Context == null || (Context as Activity).IsFinishing || ActiveCameraDevice == null) { return(Task.FromResult(Enumerable.Empty <byte>().ToArray())); } var file = new File(Context.GetExternalFilesDir(null), "pic.jpg"); var tcs = new TaskCompletionSource <byte[]>(); var readerListener = new ImageAvailableListener(tcs, file); try { CameraManager manager = (CameraManager)Context.GetSystemService(Context.CameraService); CameraCharacteristics characteristics = manager.GetCameraCharacteristics(ActiveCameraDevice.Id); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); Size[] jpegSizes = map.GetOutputSizes((int)ImageFormatType.Jpeg); int width = 640; int height = 480; if (jpegSizes != null && jpegSizes.Length > 0) { width = jpegSizes[0].Width; height = jpegSizes[0].Height; } ImageReader reader = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1); List <Surface> outputSurfaces = new List <Surface> { reader.Surface, new Surface(textureView.SurfaceTexture) }; CaptureRequest.Builder captureBuilder = ActiveCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture); captureBuilder.AddTarget(reader.Surface); SetUpCaptureRequestBuilder(captureBuilder); captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(ORIENTATIONS.Get((int)SurfaceOrientation.Rotation180))); HandlerThread thread = new HandlerThread("CameraPicture"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); reader.SetOnImageAvailableListener(readerListener, backgroundHandler); ActiveCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureSessionStateCallback(this) { OnConfiguredAction = session => { try { session.Capture(captureBuilder.Build(), null, backgroundHandler); } catch (CameraAccessException ex) { Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString()); tcs.TrySetException(ex); } } }, backgroundHandler); } catch (CameraAccessException ex) { Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace); tcs.TrySetException(ex); } return(tcs.Task); }