android studio 11版本的拍照和打开相册代码
时间: 2024-09-26 08:07:05 浏览: 33
在Android Studio 11(实际上,到目前为止,Android Studio官方还未发布第11版,目前最新稳定版是4.x系列)中,我们可以使用`CameraX`库来方便地处理相机和相册操作。以下是简单的代码示例,展示如何获取相机权限并拍照,以及打开相册让用户选择图片:
首先,确保已添加CameraX依赖。在build.gradle(Module: app)文件中添加:
```groovy
dependencies {
implementation 'androidx.camera:camera-core:1.0.0'
implementation 'androidx.camera:camera-lifecycle:1.0.0'
implementation 'androidx.camera:camera-view:1.0.0-beta06'
}
```
然后,在需要的Activity或Fragment中,请求相机和存储权限:
```java
private void requestPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_EXTERNAL_STORAGE_PERMISSION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, initialize camera
} else {
// Permission denied, handle accordingly
}
break;
case REQUEST_EXTERNAL_STORAGE_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, open gallery
} else {
// Permission denied, handle accordingly
}
break;
}
}
```
接下来,你可以使用`CameraX`来创建相机界面和拍照功能:
```java
val preview = Preview.Builder().build()
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({ cameraProvider ->
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try {
cameraProvider.bindToLifecycle(this, preview, cameraSelector) { camera, previewSession ->
// 实现拍照逻辑
val imageCapture = ImageCapture.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9)
.build()
val fileProvider = FileProvider.getUriForFile(
this, "your.app.provider.name", File("path/to/save/image.jpg"))
val photoTask = imageCapture.takePicture(previewSession, object : ImageCapture.OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy, metadata: CaptureMetadata?) {
val imageCopy = image.copyToBytes()
MediaStore.Images.Media.insertInto(ContentResolver(this@YourActivity), fileProvider, imageCopy)
}
override fun onError(error: ImageCapture.UseCaseError) {
Log.e(TAG, "onError: $error")
}
})
}
} catch (e: CameraAccessException) {
e.printStackTrace()
}
}, ContextCompat.getMainExecutor(this))
```
对于打开相册,可以使用`PickMediaItem` API:
```java
val pickResult = PickMediaItem.createIntentChooser(
this,
"Choose an image",
arrayOf(MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
).show()
if (pickResult.resultCode == RESULT_OK) {
val uri = pickResult.data ?: throw IllegalArgumentException("No data returned from pick result")
// 使用uri访问选定的照片
}
```
请注意,以上代码仅为示例,并未包含完整的错误处理和UI部分。在实际应用中,你需要适配用户交互和更多的错误处理逻辑。
阅读全文