Android studio实现打开相机或者本地上传的xml以及java代码
时间: 2024-02-26 22:57:13 浏览: 163
好的,下面是实现打开相机或本地上传的完整代码,包括 XML 和 Java 代码,供您参考:
1. 打开相机:
activity_main.xml:
```xml
<Button
android:id="@+id/btn_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拍照" />
```
MainActivity.java:
```java
private static final int REQUEST_CAPTURE_IMAGE = 100;
private Button btnCapture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCapture = findViewById(R.id.btn_capture);
btnCapture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openCamera();
}
});
}
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CAPTURE_IMAGE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
// 在这里处理拍摄的照片
}
}
```
2. 打开本地相册:
activity_main.xml:
```xml
<Button
android:id="@+id/btn_pick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择照片" />
```
MainActivity.java:
```java
private static final int REQUEST_PICK_IMAGE = 200;
private Button btnPick;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPick = findViewById(R.id.btn_pick);
btnPick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickImage();
}
});
}
private void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_PICK_IMAGE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK) {
Uri uri = data.getData();
// 在这里处理选中的照片
}
}
```
希望以上代码可以帮助您实现打开相机或本地上传的功能。
阅读全文