如何从Android中的相机获取图像

时间:2019-06-03 05:49:21

标签: android android-camera-intent

这是我正在使用的代码。

Intent takePictureIntent = new 
Intent(MediaStore.ACTION_IMAGE_CAPTURE);

if(takePictureIntent.resolveActivity(getPackageManager()) != null) {
    startActivityForResult(takePictureIntent, PICK_IMAGE_CAMERA1); 
 }

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

    if (resultCode == RESULT_OK && data != null) {
    if (requestCode==PICK_IMAGE_CAMERA1){
    Bundle extras = data.getExtras();
    Bitmap imageBitmap = (Bitmap) extras.get("data");
    imageView.setImageBitmap(imageBitmap);
 }     
}
}

我收到以下异常。

java.lang.RuntimeException: Failure delivering result 
    ResultInfo{who=null, request=5, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: url
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4360)

2 个答案:

答案 0 :(得分:0)

//This Function Called on Onclick
    private void dispatchTakePictureIntent() {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

            // Create the File where the photo should go
            File photoFile = null;

            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                ex.printStackTrace();
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {

                Uri photoURI = FileProvider.getUriForFile(this,
                        mActivity.getPackageName() + ".provider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);

            }
        }
    }

     @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case REQUEST_TAKE_PHOTO:
                    if (resultCode == Activity.RESULT_OK) {

                        Log.i(TAG, "onActivityResult: currentPHotoPath >> " + currentPhotoPath);
                        Glide.with(mContext).load(currentPhotoPath).into(imgCamera);

                    }

                    break;
            }
        }

答案 1 :(得分:0)

确保您同时具有相机权限读/写外部存储权限。