android调用图库和相机
时间: 2023-10-04 08:12:13 浏览: 48
Android 调用图库和相机需要使用系统提供的 Intent,可以使用以下代码实现:
调用系统图库:
```java
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
```
调用相机:
```java
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE);
```
其中,REQUEST_CODE_PICK_IMAGE 和 REQUEST_CODE_CAPTURE_IMAGE 是自定义的请求码,用于在 onActivityResult() 方法中区分不同的返回结果。在 onActivityResult() 方法中可以通过以下代码获取返回的图片数据:
```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_PICK_IMAGE) {
Uri selectedImage = data.getData();
// TODO 处理选择的图片
} else if (requestCode == REQUEST_CODE_CAPTURE_IMAGE) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
// TODO 处理拍摄的照片
}
}
}
```
需要注意的是,在调用相机时,拍摄的照片会以 Bitmap 的形式返回,而不是以 Uri 的形式返回。如果需要将照片保存到本地,可以参考以下代码:
```java
String fileName = "my_photo.jpg";
File file = new File(Environment.getExternalStorageDirectory(), fileName);
Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
```
其中,fileName 是保存的文件名,file 是保存的文件对象,outputFileUri 是保存的文件 Uri。需要注意的是,保存文件时需要申请 WRITE_EXTERNAL_STORAGE 权限。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)