Search code examples
imagexamarinxamarin.formstobase64string

Xamarin Forms Convert from Image to Base64 from Image Control not from file


I am loading an image from the camera into an Image control. That works beautifully as shown below.

var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });

if (photo != null)
PhotoImageRear.Source = ImageSource.FromStream(() => { return photo.GetStream(); });

I sometime later need to take the images loaded into that PhotoImageRear control and convert it to a base64 string in order to post it to an API.

What would be the most efficient way of achieving that.

Thanks in advance for your help


Solution

  • From shared code ,once you get the photo, you can use the following code to convert to Base64 .

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