android studio 拍照和相册
时间: 2023-12-06 10:38:12 浏览: 74
以下是Android Studio中拍照和相册的实现方法:
1.添加权限
在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
```
2.在布局文件中添加按钮
在布局文件中添加两个按钮,一个用于打开相机,一个用于打开相册。
```xml
<Button
android:id="@+id/btn_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开相机"/>
<Button
android:id="@+id/btn_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开相册"/>
```
3.在Activity中实现打开相机和相册的功能
在Activity中实现打开相机和相册的功能,可以使用Intent来启动系统相机和相册应用。
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_CAMERA = 1;
private static final int REQUEST_CODE_GALLERY = 2;
private Button btnCamera;
private Button btnGallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCamera = findViewById(R.id.btn_camera);
btnGallery = findViewById(R.id.btn_gallery);
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
});
btnGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_CAMERA) {
// 处理拍照结果
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
// TODO: 处理拍照结果
} else if (requestCode == REQUEST_CODE_GALLERY) {
// 处理相册选择结果
Uri uri = data.getData();
// TODO: 处理相册选择结果
}
}
}
}
```