android studio 11的拍照和打开相册 java代码
时间: 2024-09-25 14:08:42 浏览: 62
android studio 调用相机拍照,选择相册照片
5星 · 资源好评率100%
Android Studio 11(实际上是Android Studio 4.2及更高版本,因为官方并没有11这个版本)中的拍照和打开相册功能通常通过`CameraX`库和`ACTION_IMAGE_CAPTURE`或`ACTION_PICK.getImageUri()`来实现。以下是简单的示例代码:
**拍照功能:**
```java
import android.content.Intent;
import android.graphics.ImageReader;
import android.os.Bundle;
import android.util.Size;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
public class MainActivity extends AppCompatActivity {
private ImageCapture imageCapture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePhotoButton = findViewById(R.id.button_take_photo);
takePhotoButton.setOnClickListener(view -> {
openImageCapture();
});
setupCamera();
}
private void setupCamera() {
ImageCaptureConfig.Builder configBuilder = new ImageCaptureConfig.Builder()
.setTargetAspectRatio(new Size(16, 9)) // 设置图片的比例
.setCaptureMode(ImageCapture.CAPTURE_MODE_REACTIVE); // 活动模式,支持连续拍摄
ImageCaptureConfig config = configBuilder.build();
imageCapture = new ImageCapture(config);
try {
CameraX.bindToLifecycle(this, imageCapture);
} catch (Exception e) {
e.printStackTrace();
}
}
private void openImageCapture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
ImageProxy imageProxy = imageCapture.getOutputImageFromResult(data);
handleCapturedImage(imageProxy);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void handleCapturedImage(@NonNull ImageProxy imageProxy) {
imageProxy.close(); // 关闭图像代理
// ... 这里处理获取到的图片数据
}
private static final int REQUEST_IMAGE_CAPTURE = 100; // 请求码
}
```
**打开相册选择图片功能:**
```java
private void openGallery() {
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) {
if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// ... 这里处理选中的图片URI
}
super.onActivityResult(requestCode, resultCode, data);
}
private static final int REQUEST_PICK_IMAGE = 200; // 请求码
```
请注意,实际项目中还需要适配运行时权限请求、处理异常以及添加必要的错误处理代码。
阅读全文