예제 #1
0
  private void caracteristicasCamera(
      int width, int height) { // metodo responsavel por atribuir as caracteristicas das cameras

    try {
      for (String cameraId : manager.getCameraIdList()) {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

        StreamConfigurationMap map =
            characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        if (map == null) {
          continue;
        }

        // serve para atribuir o tamanho da imagem
        Size largest =
            Collections.max(
                Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea());
        imageReader =
            ImageReader.newInstance(
                largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/ 2);
        imageReader.setOnImageAvailableListener(mOnImageAvailableListener, backgroundHandler);

        // textureView.setAspectRatio(
        //       previewSize.getHeight(), previewSize.getWidth());

        return;
      }
    } catch (CameraAccessException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      informaErro
          .newInstance(getString(R.string.camera_error))
          .show(getChildFragmentManager(), FRAGMENT_DIALOG);
    }
  }
예제 #2
0
 @Override
 protected void onResume() {
   super.onResume();
   CameraManager manager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
   if (manager == null) {
     showToast(R.string.no_camera_manager);
   } else {
     try {
       mCameraIds = manager.getCameraIdList();
       boolean allCamerasAreLegacy = true;
       for (String id : mCameraIds) {
         CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);
         if (characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
             != CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
           allCamerasAreLegacy = false;
           break;
         }
       }
       if (allCamerasAreLegacy) {
         showToast(R.string.all_legacy_devices);
         getPassButton().setEnabled(false);
       }
     } catch (CameraAccessException e) {
       Toast.makeText(
               ItsTestActivity.this,
               "Received error from camera service while checking device capabilities: " + e,
               Toast.LENGTH_SHORT)
           .show();
     }
     IntentFilter filter = new IntentFilter(ACTION_ITS_RESULT);
     registerReceiver(mSuccessReceiver, filter);
   }
 }
예제 #3
0
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  public static void openCamera(CameraDevice.StateCallback stateCallback)
      throws CameraAccessException {
    Context context_holder = ApplicationContextProvider.getContext();
    CameraManager manager = (CameraManager) context_holder.getSystemService(Context.CAMERA_SERVICE);

    try {
      String cameraId = manager.getCameraIdList()[0];
      CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
      StreamConfigurationMap map =
          characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
      assert map != null;

      manager.openCamera(cameraId, stateCallback, null);

    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
    }
    ;
    Log.e("camera", "Sleep, re-try");
  }
  /**
   * 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(final int width, final int height) {
    final Activity activity = getActivity();
    final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
      for (final String cameraId : manager.getCameraIdList()) {
        final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

        // We don't use a front facing camera in this sample.
        final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
        if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
          continue;
        }

        final StreamConfigurationMap map =
            characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

        if (map == null) {
          continue;
        }

        // For still image captures, we use the largest available size.
        final Size largest =
            Collections.max(
                Arrays.asList(map.getOutputSizes(ImageFormat.YUV_420_888)),
                new CompareSizesByArea());

        sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);

        // 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(SurfaceTexture.class), inputSize, inputSize, largest);

        // We fit the aspect ratio of TextureView to the size of preview we picked.
        final int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
          textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight());
        } else {
          textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth());
        }

        CameraConnectionFragment.this.cameraId = cameraId;

        cameraConnectionCallback.onPreviewSizeChosen(previewSize, sensorOrientation);
        return;
      }
    } catch (final CameraAccessException e) {
      LOGGER.e(e, "Exception!");
    } catch (final 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);
    }
  }
  /**
   * 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(String strCameraId, int width, int height) {
    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
      for (String cameraId : manager.getCameraIdList()) {
        if (!cameraId.equalsIgnoreCase(strCameraId)) continue;

        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

        // We don't use a front facing camera in this sample.
        Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
        if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
          //                    continue;
        }

        StreamConfigurationMap map =
            characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        if (map == null) {
          continue;
        }

        // For still image captures, we use the largest available size.
        Size largest =
            Collections.max(
                Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea());
        mImageReader =
            ImageReader.newInstance(
                largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/ 2);
        mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);

        // 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.
        mPreviewSize =
            chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, largest);

        // We fit the aspect ratio of TextureView to the size of preview we picked.
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
          mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
          mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }

        mCameraId = cameraId;
        return;
      }
    } catch (CameraAccessException e) {
      e.printStackTrace();
    } catch (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);
    }
  }
 private String getCameraId() throws CameraAccessException {
   String[] ids = mCameraManager.getCameraIdList();
   for (String id : ids) {
     CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
     Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
     Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
     if (flashAvailable != null
         && flashAvailable
         && lensFacing != null
         && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
       return id;
     }
   }
   return null;
 }
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   mContext = getActivity();
   assertNotNull("Unable to get activity", mContext);
   mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
   assertNotNull("Unable to get CameraManager", mCameraManager);
   mCameraIds = mCameraManager.getCameraIdList();
   assertNotNull("Unable to get camera ids", mCameraIds);
   mHandlerThread = new HandlerThread(TAG);
   mHandlerThread.start();
   mHandler = new Handler(mHandlerThread.getLooper());
   mCameraListener = new BlockingStateCallback();
   Camera2MultiViewCtsActivity activity = (Camera2MultiViewCtsActivity) mContext;
   mTextureView[0] = activity.getTextureView(0);
   mTextureView[1] = activity.getTextureView(1);
   assertNotNull("Unable to get texture view", mTextureView);
   mCameraIdMap = new HashMap<String, Integer>();
   int numCameras = mCameraIds.length;
   mCameraHolders = new CameraHolder[numCameras];
   for (int i = 0; i < numCameras; i++) {
     mCameraHolders[i] = new CameraHolder(mCameraIds[i]);
     mCameraIdMap.put(mCameraIds[i], i);
   }
   mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
 }
예제 #8
0
  private void startCamera() {
    try {

      if (hasCameraPermission()) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
          // TODO: Consider calling
          //    ActivityCompat#requestPermissions
          // here to request the missing permissions, and then overriding
          //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
          //                                          int[] grantResults)
          // to handle the case where the user grants the permission. See the documentation
          // for ActivityCompat#requestPermissions for more details.
          showTost("Can not access camera. Permission Denied");
          return;
        }
        try {
          cameraManager.openCamera(mCameraId, cameraStateCallback, mHandler);
        } catch (SecurityException accessExc) {
          accessExc.printStackTrace();
          showTost("Could not access Camera, check app permissions");
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /** Opens the camera specified by {@link CameraConnectionFragment#cameraId}. */
 private void openCamera(final int width, final int height) {
   setUpCameraOutputs(width, height);
   configureTransform(width, height);
   final Activity activity = getActivity();
   final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
   try {
     if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
       throw new RuntimeException("Time out waiting to lock camera opening.");
     }
     manager.openCamera(cameraId, stateCallback, backgroundHandler);
   } catch (final CameraAccessException e) {
     LOGGER.e(e, "Exception!");
   } catch (final InterruptedException e) {
     throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
   }
 }
 private void startDevice() throws CameraAccessException {
   mTorchAppUid = Binder.getCallingUid();
   final String cameraId = getCameraId();
   if (DEBUG) Log.d(TAG, "startDevice(), cameraID: " + cameraId);
   mTorchCameraId = Integer.valueOf(cameraId);
   mOpeningCamera = true;
   mCameraManager.openCamera(cameraId, mTorchCameraListener, mHandler);
 }
예제 #11
0
  private void setupCamera(int width, int height) {

    try {
      if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
        throw new RuntimeException("Time out waiting to lock camera opening.");
      }
      for (String cameraId : cameraManager.getCameraIdList()) {
        CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
        if ((characteristics.get(CameraCharacteristics.LENS_FACING))
            .equals(CameraCharacteristics.LENS_FACING_BACK)) {
          StreamConfigurationMap configMap =
              characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
          Size largestImageSize =
              Collections.max(
                  Arrays.asList(configMap.getOutputSizes(ImageFormat.YUV_420_888)),
                  new Comparator<Size>() {
                    @Override
                    public int compare(Size lhs, Size rhs) {
                      return Long.signum(
                          lhs.getWidth() * lhs.getWidth() - rhs.getHeight() * rhs.getWidth());
                      // return 0;
                    }
                  });

          imgReader =
              ImageReader.newInstance(
                  largestImageSize.getWidth(),
                  largestImageSize.getHeight(),
                  ImageFormat.YUV_420_888,
                  60 * 600);
          imgReader.setOnImageAvailableListener(barcodeChecker, mHandler);
          prefferedBufferSize =
              getBestSize(configMap.getOutputSizes(SurfaceTexture.class), width, height);
          mCameraId = cameraId;
          return;
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /** Opens the camera specified by {@link Camera2BasicFragment#mCameraId}. */
 private void openCamera(String cameraId, int width, int height) {
   //        if (getActivity().checkSelfPermission(Manifest.permission.CAMERA)
   //                != PackageManager.PERMISSION_GRANTED) {
   //            requestCameraPermission();
   //            return;
   //        }
   setUpCameraOutputs(cameraId, width, height);
   configureTransform(width, height);
   Activity activity = getActivity();
   CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
   try {
     if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
       throw new RuntimeException("Time out waiting to lock camera opening.");
     }
     manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
   } catch (CameraAccessException e) {
     e.printStackTrace();
   } catch (InterruptedException e) {
     throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
   }
 }
  /** Opens the camera specified by {@link Camera2BasicFragment#mCameraId}. */
  private void openCamera(int width, int height) {
    setUpCameraOutputs(width, height);
    configureTransform(width, height);
    Activity activity = getActivity();

    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);

    try {
      if (!mCameraOpenCloseLock.tryAcquire(3500, TimeUnit.MILLISECONDS)) {
        Toast.makeText(getActivity(), "Time out waiting to open camera", Toast.LENGTH_SHORT).show();
        // throw new RuntimeException("Time out waiting to lock camera opening.");
      }
      // if(mCameraId.equals("0")) showToast("Front facing camera not working");
      // else
      manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    } catch (RuntimeException e) {
      e.printStackTrace();
    }
  }
  public void initialize() {
    try {
      mTorchCameraId = Integer.valueOf(getCameraId());
    } catch (Throwable e) {
      Log.e(TAG, "Couldn't initialize.", e);
      return;
    }

    if (mTorchCameraId != -1) {
      ensureHandler();
      if (mUseCameraInterface) {
        mCameraManager.registerAvailabilityCallback(mAvailabilityCallback, mHandler);
      }
    }
  }
 private Size getSmallestSize(String cameraId) throws CameraAccessException {
   Size[] outputSizes =
       mCameraManager
           .getCameraCharacteristics(cameraId)
           .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
           .getOutputSizes(SurfaceTexture.class);
   if (outputSizes == null || outputSizes.length == 0) {
     throw new IllegalStateException("Camera " + cameraId + "doesn't support any outputSize.");
   }
   Size chosen = outputSizes[0];
   for (Size s : outputSizes) {
     if (chosen.getWidth() >= s.getWidth() && chosen.getHeight() >= s.getHeight()) {
       chosen = s;
     }
   }
   return chosen;
 }
예제 #16
0
  // metodo responsavel por abrir a camera
  private void openCamera(int width, int height) {

    if (ContextCompat.checkSelfPermission(
            getActivity(),
            Manifest.permission.CAMERA) // verifica se tem permissao para usar a camera
        != PackageManager.PERMISSION_GRANTED) {
      requestCameraPermission();
      return;
    }

    caracteristicasCamera(width, height); // informo as dimensoes da tela

    try {

      manager.openCamera(
          cameraEscolhida, cameraDeviceStateCAllback, backgroundHandler); // abre a camera

    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  }
예제 #17
0
  @TargetApi(CAMERA_2_API_LIMIT)
  private void startCamera2(int width, int height) {
    lawg.d("startCamera2()");

    setUpCameraOutputs(width, height);
    configureTransform(width, height);
    mCamera2Manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
      if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
        throw new RuntimeException("Time out waiting to lock camera opening.");
      }
      mCamera2Manager.openCamera(mCameraId, mCamera2StateCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    } catch (SecurityException se) {
      lawg.e("SecurityException " + se);
      se.printStackTrace();
    }
  }
예제 #18
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View myView = inflater.inflate(R.layout.fragment_cam2, container, false);

    preview = (FrameLayout) myView.findViewById(R.id.camera2_preview);

    // we have to pass the camera id that we want to use to the surfaceview
    CameraManager manager = (CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
    try {
      String cameraId = manager.getCameraIdList()[0];
      mPreview = new Camera2Preview(getActivity().getApplicationContext(), cameraId);
      preview.addView(mPreview);

    } catch (CameraAccessException e) {
      Log.v(TAG, "Failed to get a camera ID!");
      e.printStackTrace();
    }

    // Add a listener to the Capture button
    btn_takepicture = (Button) myView.findViewById(R.id.btn_takepicture);
    btn_takepicture.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (mCapture
                == null) // While I would like the declare this earlier, the camara is not setup
                         // yet, so wait until now.
            mCapture = new Camera2CapturePic(getActivity().getApplicationContext(), mPreview);

            // get an image from the camera
            if (mCapture.reader != null) { // I'm sure it's setup correctly if reader is not null.
              mCapture.TakePicture(getOutputMediaFile(MEDIA_TYPE_IMAGE));
            }
          }
        });
    btn_takevideo = (Button) myView.findViewById(R.id.btn_takevideo);
    btn_takevideo.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (mVideo
                == null) // While I would like the declare this earlier, the camara is not setup
                         // yet, so wait until now.
            mVideo = new Camera2CaptureVid((AppCompatActivity) getActivity(), mPreview);

            if (mIsRecordingVideo == false) { // about to take a video
              mIsRecordingVideo = true;
              btn_takevideo.setText("Stop Recording");
              mVideo.startRecordingVideo(getOutputMediaFile(MEDIA_TYPE_VIDEO));
            } else {
              mVideo.stopRecordingVideo();
              mIsRecordingVideo = false;
              btn_takevideo.setText("Start Recording");
            }
          }
        });
    // and add video when I know how to do it.
    return myView;
  }
예제 #19
0
  private static void take_photo_new(
      CameraDevice cameraDevice, ImageView imageviewer_new_picture, String file_name) {
    Context context_holder = ApplicationContextProvider.getContext();
    CameraManager manager = (CameraManager) context_holder.getSystemService(Context.CAMERA_SERVICE);

    HandlerThread mBackgroundThread;
    mBackgroundThread = new HandlerThread("Camera Background");
    mBackgroundThread.start();
    final Handler mBackgroundHandler = new Handler(mBackgroundThread.getLooper());

    try {
      CameraCharacteristics characteristics =
          manager.getCameraCharacteristics(cameraDevice.getId());

      Size[] jpegSizes = null;
      if (characteristics != null) {
        jpegSizes =
            characteristics
                .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
                .getOutputSizes(ImageFormat.JPEG);
      }
      int width = 640;
      int height = 480;
      if (jpegSizes != null && 0 < jpegSizes.length) {
        width = jpegSizes[0].getWidth();
        height = jpegSizes[0].getHeight();
      }

      ImageReader reader = ImageReader.newInstance((width + 1), (height + 1), ImageFormat.JPEG, 1);

      final CaptureRequest.Builder captureBuilder =
          cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
      captureBuilder.addTarget(reader.getSurface());
      captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
      captureBuilder.set(
          CaptureRequest.COLOR_CORRECTION_MODE, CameraMetadata.COLOR_CORRECTION_MODE_FAST);
      captureBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF);

      captureBuilder.set(CaptureRequest.JPEG_THUMBNAIL_QUALITY, null);

      List<Surface> outputSurfaces = new ArrayList<Surface>(2);
      outputSurfaces.add(reader.getSurface());

      captureBuilder.build();

      cameraDevice.createCaptureSession(
          outputSurfaces,
          new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(CameraCaptureSession session) {
              try {
                session.capture(captureBuilder.build(), null, null);
              } catch (CameraAccessException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session) {}
          },
          mBackgroundHandler);

      Log.e("camera", "take picture... sleep");

      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
      }

      byte[] bytes;
      Image image = null;
      try {
        //                Log.e("camera", " reader"+reader.getHeight());
        image = reader.acquireLatestImage();
        image.getFormat();
        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
        bytes = new byte[buffer.capacity()];
        buffer.get(bytes);
      } finally {
        if (image != null) {
          image.close();
        }
      }

      // String file_name = "curent_photo";
      FileOutputStream out_put_stream = null;
      try {
        out_put_stream =
            ApplicationContextProvider.getContext()
                .openFileOutput(
                    file_name + ".jpg", ApplicationContextProvider.getContext().MODE_PRIVATE);
      } catch (IOException exception) {
        exception.printStackTrace();
      }
      try {
        out_put_stream.write(bytes);
        Log.e("camera", "saved picture! " + file_name);

        if (imageviewer_new_picture != null) {
          ImageView cap_picture = (ImageView) imageviewer_new_picture;
          Bitmap bitmap_found = FileIO.loadBMPPrivate(file_name, Bitmap.CompressFormat.JPEG);
          cap_picture.setImageBitmap(bitmap_found);
        }

      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (null != out_put_stream) {
          try {
            out_put_stream.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        closeCamera(cameraDevice);
      }
    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  }
  /**
   * 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 = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
      for (String cameraId : manager.getCameraIdList()) {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

        // We don't use a front facing camera in this sample.
        Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
        if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
          continue;
        }

        StreamConfigurationMap map =
            characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        if (map == null) {
          continue;
        }

        // For still image captures, we use the largest available size.
        Size largest =
            Collections.max(
                Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea());
        mImageReader =
            ImageReader.newInstance(
                largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/ 2);
        mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);

        // Find out if we need to swap dimension to get the preview size relative to sensor
        // coordinate.
        int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        //noinspection ConstantConditions
        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        boolean swappedDimensions = false;
        switch (displayRotation) {
          case Surface.ROTATION_0:
          case Surface.ROTATION_180:
            if (mSensorOrientation == 90 || mSensorOrientation == 270) {
              swappedDimensions = true;
            }
            break;
          case Surface.ROTATION_90:
          case Surface.ROTATION_270:
            if (mSensorOrientation == 0 || mSensorOrientation == 180) {
              swappedDimensions = true;
            }
            break;
          default:
            Log.e(TAG, "Display rotation is invalid: " + displayRotation);
        }

        Point displaySize = new Point();
        activity.getWindowManager().getDefaultDisplay().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;
        }

        // 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.
        mPreviewSize =
            chooseOptimalSize(
                map.getOutputSizes(SurfaceTexture.class),
                rotatedPreviewWidth,
                rotatedPreviewHeight,
                maxPreviewWidth,
                maxPreviewHeight,
                largest);

        // We fit the aspect ratio of TextureView to the size of preview we picked.
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
          mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
          mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }

        // Check if the flash is supported.
        Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
        mFlashSupported = available == null ? false : available;

        mCameraId = cameraId;
        return;
      }
    } catch (CameraAccessException e) {
      e.printStackTrace();
    } catch (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);
    }
  }
예제 #21
0
 private void verificaCameras() throws CameraAccessException { // verifica as
   Activity activity = getActivity();
   CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
   idCameras = manager.getCameraIdList();
 }