如果已经设置好了bitmap函数 需要如何去让拍照和选择图片都同时调用bitmap
时间: 2024-04-30 14:20:16 浏览: 52
如果你已经有了一个能够将图片转换成bitmap的函数,那么你可以在拍照和选择图片的回调函数中调用这个函数来获取bitmap。以下是一个示例代码:
```java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
Button cameraButton = findViewById(R.id.cameraButton);
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
Button galleryButton = findViewById(R.id.galleryButton);
galleryButton.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, 1);
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, 2);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) { // Gallery
Uri selectedImage = data.getData();
try {
Bitmap bitmap = getBitmapFromUri(selectedImage);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == 2) { // Camera
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return bitmap;
}
}
```
在这个示例代码中,拍照和选择图片的回调函数分别为 `onActivityResult` 方法中的 `requestCode` 为 `2` 和 `1` 的情况。在这两个分支中,我们分别调用了 `getBitmapFromUri` 方法来获取bitmap,并将其设置到ImageView中显示。你可以将你的bitmap转换函数放入 `getBitmapFromUri` 方法中,并将uri作为参数传递。
阅读全文