Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin android image URI to Byte array

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!

like image 760
softmarshmallow Avatar asked May 03 '17 07:05

softmarshmallow


1 Answers

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;
}
like image 176
zchpit Avatar answered Nov 06 '22 19:11

zchpit