5

i'm simply trying to upload image to server.

when i choose image from , i get URI to that image. the question is how can i convert this URI to byte[] byte array?

no more no less. thats my question

this is what ive been trying.

i tried to rewrite this https://colinyeoh.wordpress.com/2012/05/18/android-convert-image-uri-to-byte-array/ to C#

    public byte[] convertImageToByte(Android.Net.Uri uri)
    {
        byte[] data = null;
        try
        {

            ContentResolver cr = this.ContentResolver;
            var inputStream = cr.OpenInputStream(uri);
            Bitmap bitmap = BitmapFactory.DecodeStream(inputStream);
            var baos = new ByteArrayOutputStream();
            bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, baos);
            data = baos.ToByteArray();
        }
        catch (FileNotFoundException e)
        {
            e.PrintStackTrace();
        }
        return data;
    }

but the error...

Error CS1503: Argument `#3' cannot convert `Java.IO.ByteArrayOutputStream' expression to type `System.IO.Stream' (CS1503) (Foodle.Droid)

how to fix this? or new code to get image from gallery and convert that to byte array is fine.

help!

1
  • You could try reading all the data using inputStream.Read(), then using BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length); to get the image Commented May 3, 2017 at 10:37

1 Answer 1

7
public byte[] convertImageToByte(Android.Net.Uri uri)
{
    Stream stream = ContentResolver.OpenInputStream(uri);   
    byte[] byteArray;

    using (var memoryStream = new MemoryStream())
    {
       stream.CopyTo(memoryStream);
       byteArray = memoryStream.ToArray();
    }
    return byteArray;
}
Sign up to request clarification or add additional context in comments.

4 Comments

what here is to explain? User want's to take byteArray from android image object (Android.Net.Uri) and this method is doing the job.
p.s. eventualy, you can use DI and return Stream stream from android code, and use MemoryStream in shared code.
what is this fileStream?
this fileStream is just stream

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.