RangerRick
RangerRick

Reputation: 306

Convert Xamarin.Forms.Image to Byte Array

Simple Question: I have a Xamarin.Forms.Image called "image". I need it to be a byte array. I feel like this has to be a simple thing but I can't find it on the internet anywhere.

var image = Xamarin.Forms.Image();
image.source = "my_image_source.png";

//Magic code

byte[] imgByteArray = ???

Upvotes: 0

Views: 2789

Answers (1)

pinedax
pinedax

Reputation: 9356

Unfortunately, the Image class does not expose methods to access the actual image once loaded.

You will need to read the Image from the file and convert it to the Stream you are expecting.

To prevent reading the image object twice you can set the stream read to your Image control.

var image = Xamarin.Forms.Image();

var assembly = this.GetType().GetTypeInfo().Assembly;
byte[] imgByteArray = null;
using (var s = assembly.GetManifestResourceStream("my_image_source.png"))
{
    if (s != null)
    {
        var length = s.Length;
        imgByteArray = new byte[length];
        s.Read(buffer, 0, (int)length);

       image.Source = ImageSource.FromStream(() => s);
    }
}

// here imageByteArray will have the bytes from the image file or it will be null if the file was not loaded.

if (imgByteArray != null)
{
   //use your data here.
}

Hope this helps.-

Update:

This code will require adding your my_image_source.png as part of the PCL as an embedded resource.

Upvotes: 1

Related Questions