真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

Android實現(xiàn)Camera2預(yù)覽和拍照效果

簡介

10年積累的網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認識你,你也不認識我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有太白免費網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

網(wǎng)上對于 Camera2 的介紹有很多,在 Github 上也有很多關(guān)于 Camera2 的封裝庫,但是對于那些庫,封裝性太強,有時候我們僅僅是需要個簡簡單單的拍照功能而已,因此,自定義一個 Camera 使之變得輕量級那是非常重要的了。(本文并非重復(fù)造輪子, 而是在于學(xué)習(xí) Camera2API 的基本功能, 筆記之。)

學(xué)習(xí)要點:

使用 Android Camera2 API 的基本功能。
迭代連接到設(shè)備的所有相機的特征。
顯示相機預(yù)覽和拍攝照片。

Camera2 API 為連接到 Android 設(shè)備的各個相機設(shè)備提供了一個界面。 它替代了已棄用的 Camera 類。

  • 使用 getCameraIdList 獲取所有可用攝像機的列表。 然后,您可以使用 getCameraCharacteristics,并找到適合您需要的最佳相機(前 / 后面,分辨率等)。
  • 創(chuàng)建一個 CameraDevice.StateCallback 的實例并打開相機。 當相機打開時,準備開始相機預(yù)覽。
  • 使用 TextureView 顯示相機預(yù)覽。 創(chuàng)建一個 CameraCaptureSession 并設(shè)置一個重復(fù)的 CaptureRequest。
  • 靜像拍攝需要幾個步驟。 首先,需要通過更新相機預(yù)覽的 CaptureRequest 來鎖定相機的焦點。
  • 然后,以類似的方式,需要運行一個預(yù)捕獲序列。之后,它準備拍攝一張照片。 創(chuàng)建一個新的 CaptureRequest 并調(diào)用 [capture] 。

完成后,別忘了解鎖焦點。

實現(xiàn)效果

Android實現(xiàn)Camera2預(yù)覽和拍照效果環(huán)境

SDK>21

Camera2 類圖

Android實現(xiàn)Camera2預(yù)覽和拍照效果

Android實現(xiàn)Camera2預(yù)覽和拍照效果

代碼實現(xiàn)

CameraPreview.java

/**
 * Created by shenhua on 2017-10-20-0020.
 * Email shenhuanet@126.com
 */
public class CameraPreview extends TextureView {

  private static final String TAG = "CameraPreview";
  private static final SparseIntArray ORIENTATIONS = new SparseIntArray();//從屏幕旋轉(zhuǎn)轉(zhuǎn)換為JPEG方向
  private static final int MAX_PREVIEW_WIDTH = 1920;//Camera2 API 保證的最大預(yù)覽寬高
  private static final int MAX_PREVIEW_HEIGHT = 1080;
  private static final int STATE_PREVIEW = 0;//顯示相機預(yù)覽
  private static final int STATE_WAITING_LOCK = 1;//焦點鎖定中
  private static final int STATE_WAITING_PRE_CAPTURE = 2;//拍照中
  private static final int STATE_WAITING_NON_PRE_CAPTURE = 3;//其它狀態(tài)
  private static final int STATE_PICTURE_TAKEN = 4;//拍照完畢
  private int mState = STATE_PREVIEW;
  private int mRatioWidth = 0, mRatioHeight = 0;
  private int mSensorOrientation;
  private boolean mFlashSupported;

  private Semaphore mCameraOpenCloseLock = new Semaphore(1);//使用信號量 Semaphore 進行多線程任務(wù)調(diào)度
  private Activity activity;
  private File mFile;
  private HandlerThread mBackgroundThread;
  private Handler mBackgroundHandler;
  private Size mPreviewSize;
  private String mCameraId;
  private CameraDevice mCameraDevice;
  private CaptureRequest.Builder mPreviewRequestBuilder;
  private CaptureRequest mPreviewRequest;
  private CameraCaptureSession mCaptureSession;
  private ImageReader mImageReader;

  static {
    ORIENTATIONS.append(Surface.ROTATION_0, 90);
    ORIENTATIONS.append(Surface.ROTATION_90, 0);
    ORIENTATIONS.append(Surface.ROTATION_180, 270);
    ORIENTATIONS.append(Surface.ROTATION_270, 180);
  }

  public CameraPreview(Context context) {
    this(context, null);
  }

  public CameraPreview(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public CameraPreview(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    mFile = new File(getContext().getExternalFilesDir(null), "pic.jpg");
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    if (0 == mRatioWidth || 0 == mRatioHeight) {
      setMeasuredDimension(width, height);
    } else {
      if (width < height * mRatioWidth / mRatioHeight) {
        setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
      } else {
        setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
      }
    }
  }

  public void onResume(Activity activity) {
    this.activity = activity;
    startBackgroundThread();
    //當Activity或Fragment OnResume()時,可以沖洗打開一個相機并開始預(yù)覽,否則,這個Surface已經(jīng)準備就緒
    if (this.isAvailable()) {
      openCamera(this.getWidth(), this.getHeight());
    } else {
      this.setSurfaceTextureListener(mSurfaceTextureListener);
    }
  }

  public void onPause() {
    closeCamera();
    stopBackgroundThread();
  }

  public void setOutPutDir(File file) {
    this.mFile = file;
  }

  public void setAspectRatio(int width, int height) {
    if (width < 0 || height < 0) {
      throw new IllegalArgumentException("Size can't be negative");
    }
    mRatioWidth = width;
    mRatioHeight = height;
    requestLayout();
  }

  public void setAutoFlash(CaptureRequest.Builder requestBuilder) {
    if (mFlashSupported) {
      requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
          CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
    }
  }

  public void takePicture() {
    lockFocus();
  }

  private void startBackgroundThread() {
    mBackgroundThread = new HandlerThread("CameraBackground");
    mBackgroundThread.start();
    mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
  }

  private void stopBackgroundThread() {
    mBackgroundThread.quitSafely();
    try {
      mBackgroundThread.join();
      mBackgroundThread = null;
      mBackgroundHandler = null;
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  /**
   * 處理生命周期內(nèi)的回調(diào)事件
   */
  private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
      openCamera(width, height);
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
      configureTransform(width, height);
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
      return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture texture) {
    }
  };

  /**
   * 相機狀態(tài)改變回調(diào)
   */
  private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

    @Override
    public void onOpened(@NonNull CameraDevice cameraDevice) {
      mCameraOpenCloseLock.release();
      Log.d(TAG, "相機已打開");
      mCameraDevice = cameraDevice;
      createCameraPreviewSession();
    }

    @Override
    public void onDisconnected(@NonNull CameraDevice cameraDevice) {
      mCameraOpenCloseLock.release();
      cameraDevice.close();
      mCameraDevice = null;
    }

    @Override
    public void onError(@NonNull CameraDevice cameraDevice, int error) {
      mCameraOpenCloseLock.release();
      cameraDevice.close();
      mCameraDevice = null;
      if (null != activity) {
        activity.finish();
      }
    }
  };

  /**
   * 處理與照片捕獲相關(guān)的事件
   */
  private CameraCaptureSession.CaptureCallback mCaptureCallback = new CameraCaptureSession.CaptureCallback() {

    private void process(CaptureResult result) {
      switch (mState) {
        case STATE_PREVIEW: {
          break;
        }
        case STATE_WAITING_LOCK: {
          Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
          if (afState == null) {
            captureStillPicture();
          } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
              CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
            Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
            if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
              mState = STATE_PICTURE_TAKEN;
              captureStillPicture();
            } else {
              runPreCaptureSequence();
            }
          }
          break;
        }
        case STATE_WAITING_PRE_CAPTURE: {
          Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
          if (aeState == null ||
              aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
              aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
            mState = STATE_WAITING_NON_PRE_CAPTURE;
          }
          break;
        }
        case STATE_WAITING_NON_PRE_CAPTURE: {
          Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
          if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
            mState = STATE_PICTURE_TAKEN;
            captureStillPicture();
          }
          break;
        }
      }
    }

    @Override
    public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                    @NonNull CaptureRequest request,
                    @NonNull CaptureResult partialResult) {
      process(partialResult);
    }

    @Override
    public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                    @NonNull CaptureRequest request,
                    @NonNull TotalCaptureResult result) {
      process(result);
    }

  };

  /**
   * 在確定相機預(yù)覽大小后應(yīng)調(diào)用此方法
   *
   * @param viewWidth 寬
   * @param viewHeight 高
   */
  private void configureTransform(int viewWidth, int viewHeight) {
    if (null == mPreviewSize || null == activity) {
      return;
    }
    int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    Matrix matrix = new Matrix();
    RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
    float centerX = viewRect.centerX();
    float centerY = viewRect.centerY();
    if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
      bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
      matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
      float scale = Math.max(
          (float) viewHeight / mPreviewSize.getHeight(),
          (float) viewWidth / mPreviewSize.getWidth());
      matrix.postScale(scale, scale, centerX, centerY);
      matrix.postRotate(90 * (rotation - 2), centerX, centerY);
    } else if (Surface.ROTATION_180 == rotation) {
      matrix.postRotate(180, centerX, centerY);
    }
    this.setTransform(matrix);
  }

  /**
   * 根據(jù)mCameraId打開相機
   */
  private void openCamera(int width, int height) {
    setUpCameraOutputs(width, height);
    configureTransform(width, height);
    CameraManager manager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
    try {
      if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
        throw new RuntimeException("Time out waiting to lock camera opening.");
      }
      if (ActivityCompat.checkSelfPermission(activity, 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.
        return;
      }
      manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
  }

  /**
   * 關(guān)閉相機
   */
  private void closeCamera() {
    try {
      mCameraOpenCloseLock.acquire();
      if (null != mCaptureSession) {
        mCaptureSession.close();
        mCaptureSession = null;
      }
      if (null != mCameraDevice) {
        mCameraDevice.close();
        mCameraDevice = null;
      }
      if (null != mImageReader) {
        mImageReader.close();
        mImageReader = null;
      }
    } catch (InterruptedException e) {
      throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
    } finally {
      mCameraOpenCloseLock.release();
    }
  }

  /**
   * 設(shè)置相機相關(guān)的屬性或變量
   *
   * @param width 相機預(yù)覽的可用尺寸的寬度
   * @param height 相機預(yù)覽的可用尺寸的高度
   */
  @SuppressWarnings("SuspiciousNameCombination")
  private void setUpCameraOutputs(int width, int height) {
    CameraManager manager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
    try {
      for (String cameraId : manager.getCameraIdList()) {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        // 在這個例子中不使用前置攝像頭
        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;
        }

        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);

        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;
        }

        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
            rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
            maxPreviewHeight, largest);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
          setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
          setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
        mFlashSupported = available == null ? false : available;

        mCameraId = cameraId;
        return;
      }
    } catch (CameraAccessException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      Log.e(TAG, "設(shè)備不支持Camera2");
    }
  }

  /**
   * 獲取一個合適的相機預(yù)覽尺寸
   *
   * @param choices      支持的預(yù)覽尺寸列表
   * @param textureViewWidth 相對寬度
   * @param textureViewHeight 相對高度
   * @param maxWidth     可以選擇的最大寬度
   * @param maxHeight     可以選擇的最大高度
   * @param aspectRatio    寬高比
   * @return 最佳預(yù)覽尺寸
   */
  private static Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight,
                     int maxWidth, int maxHeight, Size aspectRatio) {
    List bigEnough = new ArrayList<>();
    List notBigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
      if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
          option.getHeight() == option.getWidth() * h / w) {
        if (option.getWidth() >= textureViewWidth &&
            option.getHeight() >= textureViewHeight) {
          bigEnough.add(option);
        } else {
          notBigEnough.add(option);
        }
      }
    }
    if (bigEnough.size() > 0) {
      return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0) {
      return Collections.max(notBigEnough, new CompareSizesByArea());
    } else {
      Log.e(TAG, "Couldn't find any suitable preview size");
      return choices[0];
    }
  }

  /**
   * 為相機預(yù)覽創(chuàng)建新的CameraCaptureSession
   */
  private void createCameraPreviewSession() {
    try {
      SurfaceTexture texture = this.getSurfaceTexture();
      assert texture != null;
      // 將默認緩沖區(qū)的大小配置為想要的相機預(yù)覽的大小
      texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
      Surface surface = new Surface(texture);
      mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
      mPreviewRequestBuilder.addTarget(surface);
      // 我們創(chuàng)建一個 CameraCaptureSession 來進行相機預(yù)覽
      mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
          new CameraCaptureSession.StateCallback() {

            @Override
            public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
              if (null == mCameraDevice) {
                return;
              }
              // 會話準備好后,我們開始顯示預(yù)覽
              mCaptureSession = cameraCaptureSession;
              try {
                mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                setAutoFlash(mPreviewRequestBuilder);
                mPreviewRequest = mPreviewRequestBuilder.build();
                mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
              } catch (CameraAccessException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
            }
          }, null);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  }

  /**
   * 從指定的屏幕旋轉(zhuǎn)中檢索照片方向
   *
   * @param rotation 屏幕方向
   * @return 照片方向(0,90,270,360)
   */
  private int getOrientation(int rotation) {
    return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
  }

  /**
   * 鎖定焦點
   */
  private void lockFocus() {
    try {
      // 如何通知相機鎖定焦點
      mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);
      // 通知mCaptureCallback等待鎖定
      mState = STATE_WAITING_LOCK;
      mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  }

  /**
   * 解鎖焦點
   */
  private void unlockFocus() {
    try {
      mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
          CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
      setAutoFlash(mPreviewRequestBuilder);
      mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
          mBackgroundHandler);
      mState = STATE_PREVIEW;
      mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
          mBackgroundHandler);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  }

  /**
   * 拍攝靜態(tài)圖片
   */
  private void captureStillPicture() {
    try {
      if (null == activity || null == mCameraDevice) {
        return;
      }
      final CaptureRequest.Builder captureBuilder =
          mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
      captureBuilder.addTarget(mImageReader.getSurface());
      captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
          CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
      setAutoFlash(captureBuilder);
      // 方向
      int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
      captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));
      CameraCaptureSession.CaptureCallback captureCallback
          = new CameraCaptureSession.CaptureCallback() {

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                        @NonNull CaptureRequest request,
                        @NonNull TotalCaptureResult result) {
          Toast.makeText(getContext(), "Saved: " + mFile, Toast.LENGTH_SHORT).show();
          Log.d(TAG, mFile.toString());
          unlockFocus();
        }
      };
      mCaptureSession.stopRepeating();
      mCaptureSession.abortCaptures();
      mCaptureSession.capture(captureBuilder.build(), captureCallback, null);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  }

  /**
   * 運行preCapture序列來捕獲靜止圖像
   */
  private void runPreCaptureSequence() {
    try {
      // 設(shè)置拍照參數(shù)請求
      mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
          CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
      mState = STATE_WAITING_PRE_CAPTURE;
      mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  }

  /**
   * 比較兩者大小
   */
  private static class CompareSizesByArea implements Comparator {

    @Override
    public int compare(Size lhs, Size rhs) {
      return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
          (long) rhs.getWidth() * rhs.getHeight());
    }
  }

  /**
   * ImageReader的回調(diào)對象
   */
  private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
      = new ImageReader.OnImageAvailableListener() {

    @Override
    public void onImageAvailable(ImageReader reader) {
      mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile));
    }
  };

  /**
   * 將捕獲到的圖像保存到指定的文件中
   */
  private static class ImageSaver implements Runnable {

    private final Image mImage;
    private final File mFile;

    ImageSaver(Image image, File file) {
      mImage = image;
      mFile = file;
    }

    @Override
    public void run() {
      ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
      byte[] bytes = new byte[buffer.remaining()];
      buffer.get(bytes);
      FileOutputStream output = null;
      try {
        output = new FileOutputStream(mFile);
        output.write(bytes);
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        mImage.close();
        if (null != output) {
          try {
            output.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

}

MainActivity.java

public class MainActivity extends AppCompatActivity {

  CameraPreview cameraView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    cameraView = (CameraPreview) findViewById(R.id.cameraView);
  }

  @Override
  protected void onResume() {
    super.onResume();
    cameraView.onResume(this);
  }

  @Override
  protected void onPause() {
    cameraView.onPause();
    super.onPause();
  }

  public void takePic(View view) {
    cameraView.takePicture();
  }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


  

  

資源文件 ic_capture_200px.xml


  
  

其它

Manifest 權(quán)限:




Android6.0 運行時權(quán)限未貼出。(注意:為了方便讀者手機端閱讀,本文代碼部分的成員變量使用了行尾注釋,在正常編程習(xí)慣中,請使用 /* / 注釋。)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。


網(wǎng)頁名稱:Android實現(xiàn)Camera2預(yù)覽和拍照效果
分享網(wǎng)址:http://weahome.cn/article/ijipjc.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部