日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Android App开发——使用CameraX打开前后摄像头拍照并保存(Java实现)

發(fā)布時(shí)間:2025/3/21 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android App开发——使用CameraX打开前后摄像头拍照并保存(Java实现) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

前言

開(kāi)發(fā)環(huán)境是Android studio 北極狐,CameraX1.0.0-alpha02,實(shí)現(xiàn)語(yǔ)言是Java。

創(chuàng)建工程

1.引入CameraX
在build.gradle添加要引入CameraX的版本。

//CameraXdef camerax_version = "1.0.0-alpha02"implementation "androidx.camera:camera-core:${camerax_version}"implementation "androidx.camera:camera-camera2:${camerax_version}"

2.在AndroidManifest.xml添加打開(kāi)攝像頭的權(quán)限和讀寫(xiě)文件的權(quán)限。

<uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> android:requestLegacyExternalStorage="true"

3.在工程里面新添加一個(gè)Activity。


4.CameraXDemo代碼。

public class IdentificationPhoto extends AppCompatActivity {private int REQUEST_CODE_PERMISSIONS = 101;private final String [] REQUIRED_PERMISSIONS =new String[] {"android.permission.CAMERA","android.permission.WRITE_EXTERNAL_STORAGE"};TextureView textureView;ImageView cameraFlip;private int backlensfacing = 0;private int flashLamp = 0;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_camerax_demo);//去掉導(dǎo)航欄getSupportActionBar().hide();if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//透明狀態(tài)欄getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//透明導(dǎo)航欄getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);}textureView = findViewById(R.id.view_camera);cameraFlip = findViewById(R.id.btn_switch_camera);cameraFlip.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){if(backlensfacing == 0){startCamera(CameraX.LensFacing.FRONT);backlensfacing = 1;}else if(backlensfacing == 1){startCamera(CameraX.LensFacing.BACK);backlensfacing = 0;}}});if(allPermissionsGranted()){startCamera(CameraX.LensFacing.BACK);}else {ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);}}private void startCamera(CameraX.LensFacing CAMERA_ID){unbindAll();Rational aspectRatio = new Rational(textureView.getWidth(), textureView.getHeight());Size screen = new Size(textureView.getWidth(),textureView.getHeight());PreviewConfig pConfig;Preview preview;pConfig = new PreviewConfig.Builder().setLensFacing(CAMERA_ID).setTargetAspectRatio(aspectRatio).setTargetResolution(screen).build();preview = new Preview(pConfig);preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {@Overridepublic void onUpdated(Preview.PreviewOutput output){ViewGroup parent = (ViewGroup)textureView.getParent();parent.removeView(textureView);parent.addView(textureView,0);textureView.setSurfaceTexture(output.getSurfaceTexture());updateTransform();}});final ImageCaptureConfig imageCaptureConfig ;imageCaptureConfig= new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MAX_QUALITY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).setLensFacing(CAMERA_ID).build();final ImageCapture imgCap = new ImageCapture(imageCaptureConfig);findViewById(R.id.btn_flash).setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){if (flashLamp == 0){flashLamp = 1;imgCap.setFlashMode(FlashMode.OFF);Toast.makeText(getBaseContext(), "Flash Disable", Toast.LENGTH_SHORT).show();}else if(flashLamp == 1){flashLamp = 0;imgCap.setFlashMode(FlashMode.ON);Toast.makeText(getBaseContext(), "Flash Enable", Toast.LENGTH_SHORT).show();}}});findViewById(R.id.btn_takePict).setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){File image = null;String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date());String imageFileName = "JPEG_"+ timeStamp + "_";File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);try {image = File.createTempFile(imageFileName,".jpeg",storageDir);}catch (IOException e){e.printStackTrace();}File file = new File(image.getAbsolutePath());imgCap.takePicture(file, new ImageCapture.OnImageSavedListener(){@Overridepublic void onImageSaved(@NonNull File file){String msg = "Pic saved at "+ file.getAbsolutePath();galleryAddPic(file.getAbsolutePath());Toast.makeText(getBaseContext(), msg,Toast.LENGTH_LONG).show();}@Overridepublic void onError(@NonNull ImageCapture.UseCaseError useCaseError, @NonNull String message, @Nullable Throwable cause) {String msg = "Pic saved at "+ message;Toast.makeText(getBaseContext(), msg,Toast.LENGTH_LONG).show();if (cause !=null){cause.printStackTrace();Toast.makeText(getBaseContext(), cause.toString(),Toast.LENGTH_LONG).show();}}});}});bindToLifecycle(this,preview, imgCap);}private void galleryAddPic(String currentFilePath){Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);File file = new File (currentFilePath);Uri contentUri = Uri.fromFile(file);mediaScanIntent.setData(contentUri);this.sendBroadcast(mediaScanIntent);//Toast.makeText(getBaseContext(), "saved to gallery",Toast.LENGTH_LONG).show();}private void updateTransform(){Matrix mx = new Matrix();float w = textureView.getMeasuredWidth();float h = textureView.getMeasuredHeight();float cX = w / 2f;float cY = h / 2f;int rotationDgr;int rotation = (int)textureView.getRotation();switch (rotation){case Surface.ROTATION_0:rotationDgr = 0;break;case Surface.ROTATION_90:rotationDgr = 90;break;case Surface.ROTATION_180:rotationDgr = 180;break;case Surface.ROTATION_270:rotationDgr = 270;break;default: return;}mx.postRotate((float)rotationDgr, cX,cY);textureView.setTransform(mx);}@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);if(requestCode == REQUEST_CODE_PERMISSIONS){if (allPermissionsGranted()) {startCamera(CameraX.LensFacing.BACK);}else{Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();finish();}}}private boolean allPermissionsGranted(){for(String permission : REQUIRED_PERMISSIONS){if(ContextCompat.checkSelfPermission(this, permission)!= PackageManager.PERMISSION_GRANTED){return false;}}return true;}private boolean checkCameraHardware(Context context){return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);}private void toggleFrontBackCamera(){} }

5.在布局文件里面添加

<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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=".CameraXDome"><TextureViewandroid:id="@+id/view_camera"android:layout_width="0dp"android:layout_height="0dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="1.0"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintVertical_bias="0.0" /><ImageButtonandroid:id="@+id/btn_takePict"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/ic_camera"android:layout_marginBottom="30dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintEnd_toEndOf="parent"></ImageButton><ImageButtonandroid:id="@+id/btn_flash"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/ic_flash"android:layout_marginBottom="35dp"android:layout_marginStart="20dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintStart_toStartOf="parent"></ImageButton><ImageButtonandroid:id="@+id/btn_switch_camera"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/ic_switch_camera"android:layout_marginBottom="30dp"android:layout_marginStart="330dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintStart_toStartOf="parent"></ImageButton></androidx.constraintlayout.widget.ConstraintLayout>

6.運(yùn)行APP,因?yàn)槟M器沒(méi)有前視攝像頭,上真機(jī)調(diào)試就可以看到效果。

總結(jié)

以上是生活随笔為你收集整理的Android App开发——使用CameraX打开前后摄像头拍照并保存(Java实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。