Android相機(jī)調(diào)用有原生的Camera和Camera2,我覺得調(diào)用代碼都太復(fù)雜了,CameraX調(diào)用代碼簡(jiǎn)潔很多。
說明文檔:https://developer.android.com/jetpack/androidx/releases/camera?hl=zh-cn
現(xiàn)有查到的調(diào)用資料都不夠新,對(duì)于外接攝像頭(USB攝像頭)這類非前置也非后置攝像頭的設(shè)備調(diào)用,都說是沒有實(shí)現(xiàn)。舊版本的庫可能更多目標(biāo)用戶是基于手機(jī)的,1.3.0-alpha03版本針對(duì)外接攝像頭有增加配置項(xiàng)(CameraSelector.LENS_FACING_EXTERNAL),使用該配置項(xiàng)可以實(shí)現(xiàn)外接攝像頭的調(diào)用。
0,攝像頭選擇可用值
/** A camera on the devices that its lens facing is resolved. */
public static final int LENS_FACING_UNKNOWN = -1;
/** A camera on the device facing the same direction as the device's screen. */
public static final int LENS_FACING_FRONT = 0;
/** A camera on the device facing the opposite direction as the device's screen. */
public static final int LENS_FACING_BACK = 1;
/**
* An external camera that has no fixed facing relative to the device's screen.
*
* <p>The behavior of an external camera highly depends on the manufacturer. Currently it's
* treated similar to a front facing camera with little verification. So it's considered
* experimental and should be used with caution.
*/
@ExperimentalLensFacing
public static final int LENS_FACING_EXTERNAL = 2;
1,在AndroidManifest.xml添加權(quán)限
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.any" />
2,在settings.gradle或build.gradle添加maven
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' }
}
3,在build.gradle添加依賴庫
//攝像頭預(yù)覽庫
implementation "androidx.camera:camera-core:1.3.0-alpha04"
// CameraX Camera2 extensions[可選]拓展庫可實(shí)現(xiàn)人像、HDR、夜間和美顏、濾鏡但依賴于OEM
implementation "androidx.camera:camera-camera2:1.3.0-alpha04"
// CameraX Lifecycle library[可選]避免手動(dòng)在生命周期釋放和銷毀數(shù)據(jù)
implementation "androidx.camera:camera-lifecycle:1.3.0-alpha04"
// CameraX View class[可選]最佳實(shí)踐,最好用里面的PreviewView,它會(huì)自行判斷用SurfaceView還是TextureView來實(shí)現(xiàn)
implementation 'androidx.camera:camera-view:1.3.0-alpha04'
4,開啟預(yù)覽代碼
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private PreviewView previewView;
private ProcessCameraProvider cameraProvider;
ImageView picture = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
picture = (ImageView) findViewById(R.id.picture);
previewView=findViewById(R.id.previewView);//初始化
//高版本系統(tǒng)動(dòng)態(tài)權(quán)限申請(qǐng)
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.CAMERA,
}, 11);
}
} else {
//啟動(dòng)相機(jī)
startCamera();
}
takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(picture);//取圖識(shí)別
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==11){//獲取權(quán)限后,開啟攝像頭
//啟動(dòng)相機(jī)
startCamera();
}
}
private void startCamera() {
// 請(qǐng)求 CameraProvider
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
//檢查 CameraProvider 可用性,驗(yàn)證它能否在視圖創(chuàng)建后成功初始化
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future.
// This should never be reached.
}
}, ContextCompat.getMainExecutor(this));
}
//選擇相機(jī)并綁定生命周期和用例
private void bindPreview(@NonNull ProcessCameraProvider cp) {
this.cameraProvider=cp;
Preview preview = new Preview.Builder()
.build();
@SuppressLint("UnsafeOptInUsageError")
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)//CameraSelector.LENS_FACING_EXTERNAL
.build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
cameraProvider.unbindAll();//解綁組件
cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview);
}
//拍照,這里偷懶了,直接取了預(yù)覽控件的圖片,需要拍照的再去看看官方文檔吧
public void takePhoto(View view)
{
Log.e("OCR", "takePhoto");
Bitmap bitmap = previewView.getBitmap();
view.setBackground(new BitmapDrawable(getApplicationContext().getResources(),bitmap)); //show picture
}
@Override
protected void onDestroy() {
super.onDestroy();
cameraProvider.unbindAll();
}
5,界面布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical">
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center"
/>
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="取圖"/>
<ImageView
android:id="@+id/picture"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center"
/>
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
6,測(cè)試效果(文字識(shí)別部分請(qǐng)忽略)
s
7,庫的調(diào)用版本是比較新的,建議JDK版本不要太低,我使用的是16.0.2
新人入行,經(jīng)驗(yàn)分享,如有所誤,歡迎指出~文章來源:http://www.zghlxwxcb.cn/news/detail-698407.html
版權(quán)歸屬:深圳市琪智科技有限公司-花花文章來源地址http://www.zghlxwxcb.cn/news/detail-698407.html
到了這里,關(guān)于Android相機(jī)調(diào)用-CameraX【外接攝像頭】【USB攝像頭】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!