Search This Blog

Tuesday 17 September 2019

Get image path from Content-URI in Android (Xamarin)

MainActivity.cs
Add this method in MainActivity.cs
//Here pass the URI of image and it will return full image path.
       private string GetPathToImage(global::Android.Net.Uri uri)
        {
            String[] projection = { MediaStore.Images.Media.InterfaceConsts.Data };
            var cursor = this.ContentResolver.Query(uri, projection, null, null, null);
            cursor.MoveToFirst();
            int columnIndex = cursor.GetColumnIndex(projection[0]);
            String picturePath = cursor.GetString(columnIndex); // returns null
            if (string.IsNullOrEmpty(picturePath))
            {
                string wholeID = DocumentsContract.GetDocumentId(uri);
                string id = wholeID.Split(':')[1];
                String sel = MediaStore.Images.Media.InterfaceConsts.Id + "=?";
                var externalCursor = this.ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projection, sel, new string[] { id }, null);
                int columnIndex1 = externalCursor.GetColumnIndex(projection[0]);
                if (externalCursor.MoveToFirst())
                {
                    picturePath = externalCursor.GetString(columnIndex1);
                }
            }
            //string doc_id = "";
            //using (var c1 = ContentResolver.Query(uri, null, null, null, null))
            //{
            //    c1.MoveToFirst();
            //    String document_id = c1.GetString(0);
            //    doc_id = document_id.Substring(document_id.LastIndexOf(":") + 1);
            //}
            //string path = null;

            //// The projection contains the columns we want to return in our query.
            //string selection = MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
            //Context CurrentContext = CrossCurrentActivity.Current.Activity;

            //using (var cursor = this.ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] { doc_id }, null))
            //{

            //    if (cursor == null) return path;
            //    var columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data);
            //    cursor.MoveToFirst();
            //    try
            //    {
            //        path = cursor.GetString(columnIndex);

            //    }
            //    catch(Exception ex)
            //    {

            //            path = uri.LastPathSegment;
            //    }

            //}
            return picturePath;
        }

No comments:

Post a Comment

Popular Posts