Darren Christopher
Darren Christopher

Reputation: 4779

Xamarin Android getting image data from Gallery

I am trying select an image from Gallery, which is stored in external. I then catch the data in OnActivityResult. I, then, want to get the byte array data of the selected image using these lines.

protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    ...
    var imageSelected = File.ReadAllBytes(data.Data.Path);
    ...
}

However, I got this following error: System.IO.DirectoryNotFoundException: Could not find a part of the path "/external/images/media/149144".

/external/images/media/149144 is the value of data.Data.Path. Also, note that I have added READ_EXTERNAL_STORAGE permission in my androidmanifest

Any help would be greatly appreciated.

Upvotes: 2

Views: 1612

Answers (1)

Elvis Xia - MSFT
Elvis Xia - MSFT

Reputation: 10831

I am trying select an image from Gallery, which is stored in external. I then catch the data in OnActivityResult. I, then, want to get the byte array data of the selected image using these lines.

You are getting the ContentUrl from data.Data.Path, and File.ReadAllBytes can't find a file from a ContentUrl.

If you want to get the byte data from the result, you can create a Bitmap from the ContentUrl and convert the Bitmap directly to byte array like below:

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);

    try
    {
        Bitmap bitmap = MediaStore.Images.Media.GetBitmap(this.ContentResolver, data.Data);
        using (MemoryStream stream = new MemoryStream())
        {
            bitmap.Compress(Bitmap.CompressFormat.Jpeg,100, stream);
            byte[] array=stream.ToArray();
        }

    }
    catch (Java.IO.IOException e)
    {
           //Exception Handling
    }
}

Upvotes: 2

Related Questions