无法通过Uri

时间:2018-12-30 23:53:39

标签: java android

在MainActivity中,我从相机上拍摄了一张照片,如官方文档所示:

private void dispatchTakePictureIntent() {
    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CAMERA);
    } else {
        if (Build.VERSION.SDK_INT >= 24) {
            try {
                Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
                m.invoke(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        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) {
                // Error occurred while creating the File

            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, 2);
            }
        }
    }

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

然后我将照片保存到图库中

private Uri galleryAddPic() {
    try{
       file = new File(mCurrentPhotoPath);
    MediaStore.Images.Media.insertImage(getContentResolver(),
            file.getAbsolutePath(), file.getName(), null);
    this.sendBroadcast(new Intent(
            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Log.v("UriTaken", Uri.fromFile(file).toString());
return Uri.fromFile(file);
}

然后,使用putExtra,将文件的Uri传递到下一个活动。 uri是这样的:

file:///storage/emulated/0/Android/data/com.my.name.myappname/files/Pictures/JPEG_20181231_002549_9133887087473873179.jpg

在新活动中,我检索了uri,并在使用它设置imageview之前(如果使用image.setImageURI(imageUri);它可以正常工作),我想将图像旋转到准确的方向(我不不知道为什么在图像视图中总是旋转)。 我使用以下代码:

if (getIntent().getExtras() != null) {
        imageUri = Uri.parse(getIntent().getStringExtra("uri"));

       path = getPath(imageUri);

        try {
            //filePath = getFileName(path);
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);
            Bitmap bitmap = BitmapFactory.decodeFile(path);


            Bitmap rotatedBitmap = null;

            switch (orientation) {

                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotatedBitmap = rotateImage(bitmap, 90);
                    image.setImageBitmap(rotatedBitmap);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotatedBitmap = rotateImage(bitmap, 180);

                    image.setImageBitmap(rotatedBitmap);
                    break;

                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotatedBitmap = rotateImage(bitmap, 270);

                    image.setImageBitmap(rotatedBitmap);
                    break;

                case ExifInterface.ORIENTATION_NORMAL:

                    image.setImageBitmap(bitmap);
                default:
                    rotatedBitmap = bitmap;

                    image.setImageBitmap(rotatedBitmap);
            }

        } catch (IOException e) {
            Log.w("TAG", "-- Error in setting image");

        }

这里是导致崩溃的方法:

public String getPath(Uri imageUri) {

        String wholeId = DocumentsContract.getDocumentId(imageUri);
        String id = wholeId.split(":")[1];
        String[] column = {MediaStore.Images.Media.DATA};
        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";
        Cursor cursor = getContentResolver().
                query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        column, sel, new String[]{id}, null);

        filePath = "";

        int columnIndex = cursor.getColumnIndex(column[0]);
        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        }

        cursor.close();

    return filePath;

}

在方法的第一行,我得到了上面发布的错误,无效的uri:file /// storage ........ etc 如果我从画廊得到图片,那是可行的,因为我得到了这个Uri:

content://com.android.providers.media.documents/document/image%3A97897

我不知道问题出在将图像保存在MainActivity中的方法还是在getPath()方法中。我需要做的是拍照,保存到图库中,然后在下一个活动中检索。

0 个答案:

没有答案