1

I need to Convert a xamarin forms image into a base64 format, Can anyone help me with this?

This is how i've being trying to do it, but it doesent work.

var inputStream = signatureImage.Source.GetValue(UriImageSource.UriProperty);

            //Getting Stream as a Memorystream
            var signatureMemoryStream = inputStream as MemoryStream;

            if (signatureMemoryStream == null)
            {
                signatureMemoryStream = new MemoryStream();
                inputStream.CopyTo(signatureMemoryStream);
            }

            //Adding memorystream into a byte array
            var byteArray = signatureMemoryStream.ToArray();

            //Converting byte array into Base64 string
            base64String = Convert.ToBase64String(byteArray);

"signatureImage" is the image name.

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
anslem arnolda
  • 261
  • 1
  • 7
  • 19

3 Answers3

6

Once you get your file path , you can use the following code that worked for me.

var stream = file.GetStream();
var bytes = new byte [stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
string base64 = System.Convert.ToBase64String(bytes);

I found it here

LeRoy
  • 4,189
  • 2
  • 35
  • 46
0

Image is just a control in Xamarin forms to display the image. It is not something from which you can get your image byte array out.

You will be better of using the Media Plugin and save it to disk. Then load it via memory stream and convert.

You can also use FFImageLoading. It has 2 methods which can be of use for you :

  1. GetImageAsJpgAsync(int quality = 90, int desiredWidth = 0, int desiredHeight = 0)
  2. GetImageAsPngAsync(int desiredWidth = 0, int desiredHeight = 0)

The SO question - Convert Image into byte array in Xamarin.Forms shows how to do it in Platform specific code here.

The forum thread (Convert Image to byte[]) has a good discussion on why you can't get it from the control.

Community
  • 1
  • 1
Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
  • Thanks for the reply, But isnt there any other way that i could get the image from the XAML and and convert it to a byte array other than saving and getting it? – anslem arnolda Aug 24 '16 at 07:39
0

You can do this as below as well

var base64String = Convert.ToBase64String(File.ReadAllBytes(file.Path))
Argon
  • 791
  • 1
  • 9
  • 27