您好,登錄后才能下訂單哦!
本篇內容介紹了“怎么用Android Camera實現最簡單的預覽框顯示”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
Android要預覽Camer2界面比Camera1稍微復雜一點,但是也是不難的,下面是簡單的預覽相關代碼。
1、首先要再AndroidManifest.xml中添加權限
<uses-permission android:name="android.permission.CAMERA"/>
2、創建一個xml包含控件TextureView
比如activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextureView android:id="@+id/textureView" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/btnStop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="0.8dp" android:text="stop preview" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true"/> <Button android:id="@+id/btnStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="0.8dp" android:text="start preview" android:layout_alignParentBottom="true" android:layout_toStartOf="@id/btnStop"/> </RelativeLayout>
3、在Activity創建使用 CamaerManager
(1)使用 CamaerManager.openCamera(),傳入監聽openState狀態
(2)在openState狀態里面執行預覽界面即可
(3)關閉預覽框的時候釋放一下對象就行
比如下面的MainActivity2.java代碼:
package com.lwz.camera; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureFailure; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.StreamConfigurationMap; import android.os.Bundle; import android.util.Log; import android.util.Size; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; /** * 本類使用Camera2使用簡單相機 */ public class MainActivity2 extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "Camera2Test"; private static final int REQUEST_CAMERA_PERMISSION = 80; private TextureView mTextureView; private Button mBtnStart; private Button mBtnStop; private CameraManager mCameraManager; private CameraDevice mCameraDevice; private String mCameraId = "0"; private Size previewSize; // 用于設置預覽的寬高 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e(TAG, "onCreate!"); setContentView(R.layout.activity_main); initData(); intiView(); initEvent(); } private void intiView() { mTextureView = (TextureView) findViewById(R.id.textureView); mBtnStart = (Button) findViewById(R.id.btnStart); mBtnStop = (Button) findViewById(R.id.btnStop); } private void initData() { mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); if (mCameraManager == null) { Toast.makeText(this, "獲取不到CameraService對象!", Toast.LENGTH_LONG).show(); finish(); } } private void initEvent() { mBtnStart.setOnClickListener(this); mBtnStop.setOnClickListener(this); // 對預覽View的狀態監聽 mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) { Log.i(TAG, "onSurfaceTextureAvailable width = " + width + ",height = " + height); //1、當SurefaceTexture可用的時候,設置相機參數并打開相機 initCamera(); } @Override public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) { Log.i(TAG, "onSurfaceTextureSizeChanged width = " + width + ",height = " + height); } @Override public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) { Log.i(TAG, "onSurfaceTextureDestroyed!"); return false; } @Override public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) { //正常預覽的時候,會一直打印 //Log.i(TAG, "onSurfaceTextureUpdated!"); } }); } private void initCamera() { Log.i(TAG, "initCamera"); // 2.配置前置相機,獲取尺寸及id getCameraIdAndPreviewSizeByFacing(CameraCharacteristics.LENS_FACING_FRONT); // 0為前置攝像頭,Camera api1里面定義0為后置 // 3.打開相機 openCamera(); } /*獲取cameraId及相機預覽的最佳尺寸*/ private void getCameraIdAndPreviewSizeByFacing(int lensFacingFront) { Log.i(TAG, "getCameraIdAndPreviewSizeByFacing"); try { String[] cameraIdList = mCameraManager.getCameraIdList(); //如果設備節點不可用,會阻塞在這里 Log.i(TAG, "getCameraIdAndPreviewSizeByFacing cameraIdList = " + Arrays.toString(cameraIdList)); for (String cameraId : cameraIdList) { CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics(cameraId); int deviceLevel = cameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); //硬件與api2的契合度,0-4 Log.i(TAG, "deviceLevel = " + deviceLevel); int facing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING); if (facing != lensFacingFront) { continue; } StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); Size[] outputSizes = streamConfigurationMap.getOutputSizes(SurfaceTexture.class); mCameraId = cameraId; previewSize = setOptimalPreviewSize(outputSizes, mTextureView.getMeasuredWidth(), mTextureView.getMeasuredHeight()); Log.i(TAG, "最佳預覽尺寸(w-h):" + previewSize.getWidth() + "-" + previewSize.getHeight() + ",相機id:" + mCameraId); } } catch (CameraAccessException e) { Log.e(TAG, "getCameraIdAndPreviewSizeByFacing error = " + e.getMessage()); } } /** * 打開相機,預覽是在回調里面執行的。 */ private void openCamera() { try { // 4.權限檢查 if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { requestCameraPermission(); return; } // 5.真正打開相機 Log.i(TAG, "openCamera"); mCameraManager.openCamera(mCameraId, mStateCallback, null); } catch (CameraAccessException e) { Log.e(TAG, "openCamera error = " + e.getMessage()); } } //請求相機權限 private void requestCameraPermission() { requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); } /** * 根據相機可用的預覽尺寸和用戶給定的TextureView的顯示尺寸選擇最接近的預覽尺寸 */ private Size setOptimalPreviewSize(Size[] sizes, int previewViewWidth, int previewViewHeight) { List<Size> bigEnoughSizes = new ArrayList<>(); List<Size> notBigEnoughSizes = new ArrayList<>(); for (Size size : sizes) { if (size.getWidth() >= previewViewWidth && size.getHeight() >= previewViewHeight) { bigEnoughSizes.add(size); } else { notBigEnoughSizes.add(size); } } if (bigEnoughSizes.size() > 0) { return Collections.min(bigEnoughSizes, new Comparator<Size>() { @Override public int compare(Size lhs, Size rhs) { return Long.signum((long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight()); } }); } else if (notBigEnoughSizes.size() > 0) { return Collections.max(notBigEnoughSizes, new Comparator<Size>() { @Override public int compare(Size lhs, Size rhs) { return Long.signum((long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight()); } }); } else { Log.e(TAG, "未找到合適的預覽尺寸"); return sizes[0]; } } //關閉相機,釋放對象 private void releaseCamera() { if (mCameraDevice != null) { mCameraDevice.close(); mCameraDevice = null; } } /** * 相機狀態監聽對象 */ private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(CameraDevice camera) { Log.i(TAG, "StateCallback! onOpened"); mCameraDevice = camera; // 打開成功,保存代表相機的CameraDevice實例 SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture(); surfaceTexture.setDefaultBufferSize(mTextureView.getWidth(), mTextureView.getHeight()); Surface surface = new Surface(surfaceTexture); ArrayList<Surface> previewList = new ArrayList<>(); previewList.add(surface); try { // 6.將TextureView的surface傳遞給CameraDevice mCameraDevice.createCaptureSession(previewList, new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession session) { try { CaptureRequest.Builder builder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); builder.addTarget(surface); // 必須設置才能正常預覽 CaptureRequest captureRequest = builder.build(); // 7.CameraCaptureSession與CaptureRequest綁定(這是最后一步,已可顯示相機預覽) session.setRepeatingRequest(captureRequest, mSessionCaptureCallback, null); } catch (CameraAccessException e) { Log.e(TAG, "createCaptureRequest error = " + e.getMessage()); } } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { Log.e(TAG, "onConfigureFailed"); } }, null); } catch (CameraAccessException e) { Log.e(TAG, "createCaptureSession error = " + e.getMessage()); } } @Override public void onDisconnected(@NonNull CameraDevice camera) { Log.e(TAG, "StateCallback! onDisconnected camera.getId() = " + camera.getId()); releaseCamera(); } @Override public void onError(@NonNull CameraDevice camera, int error) { Log.e(TAG, "StateCallback camera.getId() = " + camera.getId() + " , error = " + error); releaseCamera(); } }; //預覽情況回調 private CameraCaptureSession.CaptureCallback mSessionCaptureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) { super.onCaptureStarted(session, request, timestamp, frameNumber); // 正常預覽會一直刷新 //Log.i(TAG, "mSessionCaptureCallback onCaptureStarted frameNumber =" + frameNumber); } @Override public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request, CaptureResult partialResult) { super.onCaptureProgressed(session, request, partialResult); Log.i(TAG, "mSessionCaptureCallback onCaptureProgressed request =" + request); } @Override public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) { super.onCaptureFailed(session, request, failure); Log.e(TAG, "mSessionCaptureCallback onCaptureFailed request =" + request); } @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { super.onCaptureCompleted(session, request, result); // 正常預覽時會一直刷新 //Log.i(TAG, "mSessionCaptureCallback onCaptureCompleted request =" + request); } }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnStart: Log.i(TAG, "btnStart!"); openCamera(); break; case R.id.btnStop: Log.i(TAG, "btnStop!"); releaseCamera(); break; default: } } @Override protected void onDestroy() { super.onDestroy(); releaseCamera(); } }
Camera1的使用更簡單,但是Camera1新增功能會少一點。
Camaera1的簡單使用:Android Camera1實現預覽框顯示
“怎么用Android Camera實現最簡單的預覽框顯示”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。