Android Image Crop Uri Exception

2019-05-16 14:47发布

first up, I am using Xamarin, but the problem is the same on a native Java project. I was updating the SDK to 5.1 and encountered a strange error on code that worked fine before.

  imageStream = "file://" + imageStream;

            Mvx.Trace("path: " + imageStream);

            img = imageStream;

            try {
                Intent cropIntent = new Intent("com.android.camera.action.CROP");
                // indicate image type and Uri
                var fileUri = Android.Net.Uri.Parse(imageStream);
                cropIntent.SetDataAndType(fileUri, "image/*");
                // set crop properties
                cropIntent.PutExtra("crop", "true");

                // indicate aspect of desired crop
                cropIntent.PutExtra("aspectX", 5);
                cropIntent.PutExtra("aspectY", 4);
                // indicate output X and Y
                cropIntent.PutExtra("outputX", 1000);
                cropIntent.PutExtra("outputY", 800);
                // retrieve data on return
                cropIntent.PutExtra("return-data", true);

                // start the activity - we handle returning in onActivityResult
                StartActivityForResult(cropIntent, PIC_CROP);
            }

imageStream ist the file's path. The image cropper itself load up fine and works. However when I hit save I get the following exception in logcat:

E/AndroidRuntime( 5333): FATAL EXCEPTION: BackgroundTask #1
E/AndroidRuntime( 5333): Process: com.google.android.apps.photos, PID: 5333
E/AndroidRuntime( 5333): java.lang.IllegalArgumentException: mediaStoreUri must be a MediaStore Uri

I didn't find a similar method to the Android.Net.Uri.Parse in the MediaStore or MediaStore.Image namespaces. Does this mean I would first have to save the image to MediaStore and then retrieve it before calling the intent? Or is there an obvious solution which I simply missed?

Cheers Tom

1条回答
孤傲高冷的网名
2楼-- · 2019-05-16 15:44

Ok it seems I really missed something here, extended the code for the uri retrieval to put the image into the media store first.

var file = new Java.IO.File(imageStream);
var bmp = BitmapFactory.DecodeFile(file.AbsolutePath);
img = MediaStore.Images.Media.InsertImage(ContentResolver, bmp, "" ,"");
var fileUri = Android.Net.Uri.Parse(img);

I feel like this maybe overkill, if so feel free to comment. But at least it solves the issue.

查看更多
登录 后发表回答