android studio调用相机拍照
时间: 2023-05-01 09:02:17 浏览: 165
android 调用照相机拍照
5星 · 资源好评率100%
Android Studio调用相机拍照的步骤:
1.在AndroidManifest.xml文件中添加相机权限
<uses-permission android:name="android.permission.CAMERA"/>
2.创建一个ImageView组件用于显示拍照后的照片
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3.在项目中创建一个java类来处理拍照的逻辑
private void takePhoto(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "takePhoto: " + ex.getMessage());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,"com.example.android.fileprovider",photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
}
4.在onActivityResult中获取拍照结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
阅读全文