0

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 = ???
1
  • Is it a restriction that you use the Xamarin.Forms Image? If not you can simply start using FFImageLoading instead! it has a method that can give you a stream which can be converted into byte array Commented Oct 17, 2019 at 7:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.