android - 在 Android Api 上拍照时空指针异常 >=23

标签 android camera

我已经搜索了很多但没有任何帮助,所以我发布了我自己的问题。

我的问题是在 Android Marshmallow 及以上版本中拍照时出现错误

java.lang.NullPointerException: uri

注意:它在 Api Level 22 以下工作正常

我的代码是

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
        return;
    }

    if (requestCode == GALLERY) {
        filePath = data.getData();
Uri uri = data.getData();
                // imageView.setImageURI(uri);
                try {

                    Log.d("waqarr",""+ Arrays.toString(convert(getPath(filePath))));
                    File f = new File(getPath(filePath));
                    file_name = f.getName();

                    Uri selectedImage = data.getData();
                    //ShowImageDialog();
                    if(filePath!= null)
                    {
                        multipart();
                    }
                    } catch (IOException e) {
                    e.printStackTrace();
                }
    }
    } else if (requestCode == CAMERA) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");

       // filePath = getImageUri(getApplicationContext(), photo);
        filePath = data.getData();
        try {

            Log.d("waqarr", "  " + Arrays.toString(convert(getPath(filePath))));
            File f = new File(getPath(filePath));
            file_name = f.getName();

            multipart();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }} public String getPath(Uri uri)
{
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();
    cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();
    return path;
}

我们将不胜感激。

最佳答案

Add below code in your Fragment/Activity to select image from camera or gallery. This are the int values for your camera or gallery request

public static final int MY_PERMISSIONS_REQUEST_CAMERA = 001;
public static final int MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE = 002;

User camera class of android to set the aspects and fixed size of camera image

Camera camera;
camera = new Camera.Builder()
            .resetToCorrectOrientation(true) // it will rotate the camera bitmap to the correct orientation from meta data
            .setTakePhotoRequestCode(1)
            .setDirectory("pics")
            .setName("PicName_" + System.currentTimeMillis())
            .setImageFormat(Camera.IMAGE_JPEG)
            .setCompression(75)
            .setImageHeight(1000) // it will try to achieve this height as close as possible maintaining the aspect ratio;
            .build(this);

Check Required permissions

if (ContextCompat.checkSelfPermission(getContext(),
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity)
                getContext(), Manifest.permission.CAMERA)) {


        } else {
            ActivityCompat.requestPermissions((Activity) getContext(),
                    new String[]{Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_CAMERA);
        }
    }

 if (ContextCompat.checkSelfPermission(getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity)
                getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {


        } else {
            ActivityCompat.requestPermissions((Activity) getContext(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE);
        }
    }

Choose Image From Gallery

/* Choose an image from Gallery */
void openImageChooser() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, SELECT_PICTURE);
}

Take picture from camera

textCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                camera.takePicture();
            }catch (Exception e){
                e.printStackTrace();
            }

            dialog.dismiss();
        }
    });

On activity result, get selected image in the form of bitmap/base64 as per your choice

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK) {
        try {
            final Uri imageUri = data.getData();
            final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri);
            final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            selectedImage.compress(Bitmap.CompressFormat.PNG, 40, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            Log.e("byte_array ", byteArray.toString());
            imgBase = Base64.encode(byteArray);

            imagePath = "data:image/png;base64," + imgBase;

            Log.e("path_of_gallery", imgBase.toString());

            // Set the image in ImageView
            imgUserProfilePicture.setImageBitmap(selectedImage);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } else {

        Bitmap bitmap = camera.getCameraBitmap();
        if(bitmap != null) {
            imgUserProfilePicture.setImageBitmap(bitmap);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            Log.e("byte_array ", byteArray.toString());
            imgBase = Base64.encode(byteArray);
            imagePath = "data:image/png;base64," + imgBase;

            Log.e("path_of_camera_img", imgBase.toString());
        }else{
            Toast.makeText(context,"Picture not taken!",Toast.LENGTH_SHORT).show();
        }
    }
}

关于android - 在 Android Api 上拍照时空指针异常 >=23,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54646184/

相关文章:

java - 我无法将 Java 完美地转换为 Kotlin

java - 如何在android中设置带有包装内容的最大高度?

javascript - iOS 文件上传时缺少选项 "Upload Photo or Video"

ios - 如何使用 ARKit 或 Apple Vision 测量 3d 对象的尺寸?

ios - 静音 Cordova 插件 cordova-plugin-camera-preview

java - 相机在 Y 轴上的移动

java - 透明 Activity 内容与父级不匹配

android - java.lang.SecurityException : Requires READ_PHONE_STATE: Neither user 10210 nor current process. 。仅限 HTC 手机

android - 如何为按钮添加模糊的阴影?

快速核心数据: save images from camera