Android App开发——使用CameraX打开前后摄像头拍照并保存(Java实现)
前言
开发环境是Android studio 北极狐,CameraX1.0.0-alpha02,实现语言是Java。
创建工程
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添加打开摄像头的权限和读写文件的权限。
<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.在工程里面新添加一个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);//去掉导航栏getSupportActionBar().hide();if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//透明状态栏getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//透明导航栏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.运行APP,因为模拟器没有前视摄像头,上真机调试就可以看到效果。
Android App开发——使用CameraX打开前后摄像头拍照并保存(Java实现)相关推荐
- Android APP开发
Android APP开发 Android 是基于Linux平台的.开源的.智能手机操作系统.Android APP开发现在使用比较广泛的程序语言是Java,Java是安卓APP开发的基础,我们在上学 ...
- Android APP开发入门
Android APP开发入门 目录 android_studio很好用的一个就是debug 1 1导入demo编译出错 1 4使用as运行安装不了apk安装adb 2 5SeekBar组件使用 2 ...
- Android App开发基础
Android App开发基础 App的开发特点 (1)App的运行环境 1.使用数据线把手机连到电脑上 2.在电脑上安装手机的驱动程序 3.打开手机的开发者选项并启用USB调试 4.将连接的手机设为 ...
- 写给Android App开发人员看的Android底层知识合集(1-8)
写给Android App开发人员看的Android底层知识合集(1-8) 转自包老师:http://www.cnblogs.com/Jax/p/6864103.html 写给Android App开 ...
- 傻瓜式Android APP开发入门教程
这篇文章主要介绍了Android APP开发入门教程,从SDK下载.开发环境搭建.代码编写.APP打包等步骤一一讲解,非常简明的一个Android APP开发入门教程,android各种机子和rom的 ...
- Cordova+Vue实现Android APP开发(二)-- 打包运行在真机上和打包运行在本地调试,以及打包时候一些问题的处理
接上一篇文章:Cordova+Vue实现Android APP开发(一) 一.使用cordova打包运行app 打包静态资源,没有问题的,但是把自己的vue其他项目转成android app时候,发现 ...
- 《Android App开发进阶与项目实战》资源下载和内容勘误
资源下载 下面是<Android App开发进阶与项目实战>一书用到的工具和代码资源: 1.本书使用的Android Studio版本为4.2,最新的安装包可前往Android官网页面下载 ...
- 我的新书《Android App开发入门与实战》已经出版
文章目录 1. 前言 2. 写书的目的 3. 书籍简介 4. 书籍目标读者群体 5. 书籍比较 6. 书籍特色 7. 书籍章节 8. 书籍封面 9. 购书地址 10. 本书案例及源码下载 1. 前言 ...
- java安卓app开发教程,Android app开发入门 —— your 'Hello, World'
从这篇可以掌握到 Android app开发环境的搭建 开发工具介绍及安装 创建你的"Hello, World" 工程结构的介绍 工程gradle配置 简单布局 代码sample ...
最新文章
- 身份证号信息后台匹配
- bzoj1607: [Usaco2008 Dec]Patting Heads 轻拍牛头
- httphandlers 与 httpmodules
- SAP Spartacus home 页面的 cx-page-slot selector
- 使用async读取异步数据
- 三网物联卡的优缺点有哪些
- 读大师的书 说自己的话——《传世经典书丛评注版》邀你来点评
- textContent与innerText
- 2018年深圳杯论文_2018.5.21/建模日记/深圳杯
- 郝斌老师c语言笔记 TXT,郝斌老师c语言笔记
- iOS 模拟器调试web/h5代码
- Python27 No module named PIL解决方法
- mac php 连接 mssql 2008,php5.3.x连接MSSQLserver2008
- 案例分享 | 某券商利用AI技术进行告警关联分析(上)
- 【思维导图】对外经济贸易大学公开课:企业财务报表分析
- 解决element 分页组件,搜索过后current-page 绑定的数据变了,但是页面当前页码并没有变的问题
- 达达,不能只做京东的达达
- Python中strip函数几种用法
- 使用genymotion模拟器下载软件出现unfortunately browser has stopped错误
- python实现任意url转存为图片