如何显示对话框以拍照或从图库中选择图片

时间:2019-05-10 15:27:03

标签: android

我需要制作一个应用程序,您可以在其中拍照并从图库中加载图片。
我可以拍照并将其加载到屏幕上,也可以从图库中拍照,但是现在有2个按钮。我的问题是如何“弹出对话框”,您可以在其中拍照或从图库中导入图片。

public class MainActivity extends AppCompatActivity {


    ImageView imageView;
    Button btnTakeImg;
    Uri imageUri;



    private static final int PICK_IMAGE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnCamera = findViewById(R.id.btnCamera);
        imageView = (ImageView)findViewById(R.id.imageView);
        btnTakeImg = (Button)findViewById(R.id.btnTakeImg);



        // Open camera and take picture
        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 0);

            }
        });



        // Pick image from gallery
        btnTakeImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });

    }
    private void openGallery() {
        Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        startActivityForResult(gallery, PICK_IMAGE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
            imageUri = data.getData();
            imageView.setImageURI(imageUri);
        }
        if(resultCode == RESULT_OK && requestCode == 0){
            Bitmap bitmap = (Bitmap)data.getExtras().get("data");
            imageView.setImageBitmap(bitmap);
        }

    }

}

1 个答案:

答案 0 :(得分:0)

您可以参考此链接Util class to pick image from gallery or from camera

编辑1: 从相机捕获图像

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);

从图库中选择

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);

处理结果:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
switch(requestCode) {
case 0:
    if(resultCode == RESULT_OK){  
        Uri selectedImage = imageReturnedIntent.getData();
        imageview.setImageURI(selectedImage);
    }

break; 
case 1:
    if(resultCode == RESULT_OK){  
        Uri selectedImage = imageReturnedIntent.getData();
        imageview.setImageURI(selectedImage);
    }
break;
}
}