Java Code Examples for android.hardware.camera2.CameraManager#openCamera()

The following examples show how to use android.hardware.camera2.CameraManager#openCamera() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Camera2DeviceTester.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
public CameraDevice captureCameraDevice() throws Exception {
    CameraManager manager =
            (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
    String id = manager.getCameraIdList()[0];
    synchronized (this) {
        manager.openCamera(id, this, sHandler);
        wait();
    }
    return mCamera;
}
 
Example 2
Source File: VideoCameraActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initCamera() {
  try {
    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String[] cameraIds = cameraManager.getCameraIdList();
    if (cameraIds.length == 0) return;

    String cameraId = cameraIds[0];

    if (ActivityCompat.checkSelfPermission(this,
      Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this,
        new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSIONS_REQUEST);
    }

    cameraManager.openCamera(cameraId, cameraDeviceCallback, null);
  } catch (CameraAccessException e) {
    Log.d(TAG, "No access to the camera.", e);
  }
}
 
Example 3
Source File: BlockingCameraManager.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
OpenListener(CameraManager manager, String cameraId,
        CameraDevice.StateCallback listener, Handler handler)
        throws CameraAccessException {
    mCameraId = cameraId;
    mProxy = listener;
    manager.openCamera(cameraId, this, handler);
}
 
Example 4
Source File: DoorbellCamera.java    From androidthings-cameraCar with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
public void initializeCamera(Context context,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
    String[] camIds = {};
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.d(TAG, "Cam access exception getting IDs", e);
    }
    if (camIds.length < 1) {
        Log.d(TAG, "No cameras found");
        return;
    }
    String id = camIds[0];
    Log.d(TAG, "Using camera id " + id);

    // Initialize the image processor
    mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
            ImageFormat.JPEG, MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(
            imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(id, mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
 
Example 5
Source File: CameraOperator.java    From android-robocar with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void init(Context context) throws CameraAccessException {
  inSession = false;

  if (!ImageSaver.isExternalStorageWritable()) {
    Timber.e("Cannot save file, external storage is not writable.");
    return;
  }

  File root = ImageSaver.getRoot(ROBOCAR_FOLDER);
  if (root == null) {
    Timber.e("Failed to create destination folder.");
    return;
  }

  CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
  String[] cameras = manager.getCameraIdList();
  if (cameras.length == 0) {
    Timber.e("No cameras available.");
    return;
  }

  Timber.d("Default camera selected (%s), %d cameras found.",
      cameras[CAMERA_INDEX], cameras.length);

  if (ActivityCompat.checkSelfPermission(
      context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    Timber.d("Camera permission not granted yet, restart your device.");
    return;
  }

  // Debug and check for autofocus support
  dumpFormatInfo(manager, cameras[CAMERA_INDEX]);

  startBackgroundThread();
  deviceCallback = new DeviceCallback();
  manager.openCamera(cameras[CAMERA_INDEX], deviceCallback, backgroundHandler);
}
 
Example 6
Source File: CameraHandler.java    From androidthings-imageclassifier with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
@SuppressLint("MissingPermission")
public void initializeCamera(Context context, int previewWidth, int previewHeight,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    if (initialized) {
        throw new IllegalStateException(
                "CameraHandler is already initialized or is initializing");
    }
    initialized = true;

    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    String[] camIds = null;
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.w(TAG, "Cannot get the list of available cameras", e);
    }
    if (camIds == null || camIds.length < 1) {
        Log.d(TAG, "No cameras found");
        return;
    }
    Log.d(TAG, "Using camera id " + camIds[0]);

    // Initialize the image processor
    mImageReader = ImageReader.newInstance(previewWidth, previewHeight, ImageFormat.JPEG,
            MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(camIds[0], mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
 
Example 7
Source File: CameraHandler.java    From androidthings-imageclassifier with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
@SuppressLint("MissingPermission")
public void initializeCamera(Context context, int previewWidth, int previewHeight,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    if (initialized) {
        throw new IllegalStateException(
                "CameraHandler is already initialized or is initializing");
    }
    initialized = true;

    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    String[] camIds = null;
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.w(TAG, "Cannot get the list of available cameras", e);
    }
    if (camIds == null || camIds.length < 1) {
        Log.d(TAG, "No cameras found");
        return;
    }
    Log.d(TAG, "Using camera id " + camIds[0]);

    // Initialize the image processor
    mImageReader = ImageReader.newInstance(previewWidth, previewHeight, ImageFormat.JPEG,
            MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(camIds[0], mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
 
Example 8
Source File: CameraHandler.java    From androidthings-imageclassifier with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
@SuppressLint("MissingPermission")
public void initializeCamera(Context context, int previewWidth, int previewHeight,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    if (initialized) {
        throw new IllegalStateException(
                "CameraHandler is already initialized or is initializing");
    }
    initialized = true;

    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    String[] camIds = null;
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.w(TAG, "Cannot get the list of available cameras", e);
    }
    if (camIds == null || camIds.length < 1) {
        Log.d(TAG, "No cameras found");
        return;
    }
    Log.d(TAG, "Using camera id " + camIds[0]);

    // Initialize the image processor
    mImageReader = ImageReader.newInstance(previewWidth, previewHeight, ImageFormat.JPEG,
            MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(camIds[0], mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
 
Example 9
Source File: CameraHandler.java    From sample-tensorflow-imageclassifier with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
@SuppressLint("MissingPermission")
public void initializeCamera(Context context, Handler backgroundHandler, Size minSize,
                             ImageReader.OnImageAvailableListener imageAvailableListener)
    throws CameraAccessException {
    if (initialized) {
        throw new IllegalStateException(
                "CameraHandler is already initialized or is initializing");
    }
    initialized = true;
    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    String camId = getCameraId(context);

    // Initialize the image processor with the largest available size.
    CameraCharacteristics characteristics = manager.getCameraCharacteristics(camId);
    StreamConfigurationMap map = characteristics.get(
        CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

    Size bestSize = getBestCameraSize(map.getOutputSizes(ImageFormat.JPEG), minSize);
    if (bestSize == null) {
        throw new RuntimeException("We could not find a camera resolution that is larger than "
                + minSize.getWidth() + "x" + minSize.getHeight());
    }

    mImageReader = ImageReader.newInstance(bestSize.getWidth(), bestSize.getHeight(),
        ImageFormat.JPEG, MAX_IMAGES);
    mImageDimensions = bestSize;
    Log.d(TAG, "Will capture photos that are " + mImageDimensions.getWidth() + " x " +
        mImageDimensions.getHeight());
    mImageReader.setOnImageAvailableListener(imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(camId, mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.e(TAG, "Camera access exception", cae);
    }
}
 
Example 10
Source File: CameraUtil.java    From AndroidDemo with MIT License 5 votes vote down vote up
@SuppressLint("MissingPermission")
@RequiresPermission(android.Manifest.permission.CAMERA)
private void openCamera(CameraManager cameraManager, CameraConfig config) {
    try {
        cameraManager.openCamera(config.cameraId, config.cameraStateCallback, handler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
 
Example 11
Source File: DoorbellCamera.java    From doorbell with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
public void initializeCamera(Context context,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
    String[] camIds = {};
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.e(TAG, "Cam access exception getting IDs", e);
    }
    if (camIds.length < 1) {
        Log.e(TAG, "No cameras found");
        return;
    }
    String id = camIds[0];
    Log.d(TAG, "Using camera id " + id);

    // Initialize the image processor
    mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
            ImageFormat.JPEG, MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(
            imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(id, mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
 
Example 12
Source File: CameraActivity.java    From Chinese-number-gestures-recognition with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@SuppressLint("NewApi")
    private void initCamera2() {
        findViewById(R.id.btn_control).setClickable(true);

        HandlerThread handlerThread = new HandlerThread("Camera2");
        handlerThread.start();
        childHandler = new Handler(handlerThread.getLooper());
        mainHandler = new Handler(getMainLooper());


        mCameraID = BACK_CAMERA;//后摄像头
        Log.d(TAG, "initCamera2: "+ CameraCharacteristics.LENS_FACING_BACK);
        mImageReader = ImageReader.newInstance(1080, 1920, ImageFormat.JPEG,1);
        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            //可以在这里处理拍照得到的临时照片 例如,写入本地
            @Override
            public void onImageAvailable(ImageReader reader) {
//                mCameraDevice.close();
//                mSurfaceView.setVisibility(View.INVISIBLE);
                // 拿到拍照照片数据
                Image image = reader.acquireNextImage();
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);//由缓冲区存入字节数组
                //保存

                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                if (bitmap != null) {
                    if(mCameraID == FRONT_CAMERA){
                        //前置摄像头拍的要先旋转180度
                        bitmap = adjustPhotoRotation(bitmap,180);
                    }
                    iv_thumb.setImageBitmap(bitmap);
                    writeToFile(bitmap);
                }

                image.close();

                //缩放得到用于显示的图片 128*128
                Bitmap displayBitmap = scaleImage(bitmap,128,128);
                //缩放得到用于预测的图片 64*64
                Bitmap bitmapForPredit = scaleImage(bitmap,64,64);

//                //把图片保存到本地图库
                //MediaStore.Images.Media.insertImage(getContentResolver(), bitmapForPredit, "title", "description");

                //加载模型
                classifier = new Classifier(getAssets(),MODEL_FILE);
                ArrayList<String> result = classifier.predict(bitmapForPredit);
                //传递参数
                Bundle bundle = new Bundle();
                bundle.putParcelable("image",displayBitmap);
                bundle.putStringArrayList("recognize_result",result);
                Intent intent = new Intent(CameraActivity.this, DisplayResult.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }

        }, mainHandler);
        //获取摄像头管理
        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            //打开摄像头
            mCameraManager.openCamera(mCameraID+"", stateCallback, mainHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
 
Example 13
Source File: CameraActivity.java    From CameraDemo with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")
    private void initCamera2() {
        findViewById(R.id.btn_control).setClickable(true);

        HandlerThread handlerThread = new HandlerThread("Camera2");
        handlerThread.start();
        childHandler = new Handler(handlerThread.getLooper());
        mainHandler = new Handler(getMainLooper());


        mCameraID = BACK_CAMERA;//后摄像头
        Log.d(TAG, "initCamera2: "+ CameraCharacteristics.LENS_FACING_BACK);
        mImageReader = ImageReader.newInstance(1080, 1920, ImageFormat.JPEG,1);
        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() { //可以在这里处理拍照得到的临时照片 例如,写入本地
            @Override
            public void onImageAvailable(ImageReader reader) {
//                mCameraDevice.close();
//                mSurfaceView.setVisibility(View.INVISIBLE);
                // 拿到拍照照片数据
                Image image = reader.acquireNextImage();
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);//由缓冲区存入字节数组
                //保存

                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                if (bitmap != null) {
                    if(mCameraID == FRONT_CAMERA){
                        //前置摄像头拍的要先旋转180度
                        bitmap = adjustPhotoRotation(bitmap,180);
                    }
                    iv_thumb.setImageBitmap(bitmap);
                    writeToFile(bitmap);
                }

                image.close();
            }
        }, mainHandler);
        //获取摄像头管理
        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            //打开摄像头
            mCameraManager.openCamera(mCameraID+"", stateCallback, mainHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }