If what you want is a string representation of a Image then first you need to get the bytes from this image and then convert it into a string format like Base64
But first we need to get the byte from the image, Xamarin.Forms's Image is a View which contains a Source
public class Image : View, IImageController, IElementConfiguration<Image> { public ImageSource Source { get; set; } }
That source is used to load the image that will be shown, we have a some kinds of ImageSource (FileImageSource, StreamImageSource, UriImageSource) but if I'm not mistaken currently no way to transform ImageSource to bytes in Xamarin.Forms, but we can use native code for such
Android
In Android we can use IImageSourceHandler to transform an ImageSource to Bitmap and form the Bitmap to bytes
[assembly: Dependency(typeof(ImageLoader))] public class ImageLoader : IImageLoader { public async Task<byte[]> LoadImageAsync(ImageSource source) { IImageSourceHandler handler = GetHandlerFor(source); var bmp = await handler.LoadImageAsync(source, Forms.Context); byte[] result; using (Stream ms = new MemoryStream()) { await bmp.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 95, ms); result = new byte[ms.Length]; ms.Position = 0; await ms.ReadAsync(result, 0, (int)ms.Length); } return result; } private IImageSourceHandler GetHandlerFor(ImageSource source) { IImageSourceHandler result; if (source is FileImageSource) result = new FileImageSourceHandler(); else if (source is StreamImageSource) result = new StreamImagesourceHandler(); else result = new ImageLoaderSourceHandler(); return result; } }
iOS
Same as Android we can use IImageSourceHandler to transform into UIImage and then get the bytes from it
[assembly: Dependency(typeof(ImageLoader))] public class ImageLoader : IImageLoader { public async Task<byte[]> LoadImageAsync(ImageSource source) { IImageSourceHandler handler = GetHandlerFor(source); UIImage image = await handler.LoadImageAsync(source); using (NSData imageData = image.AsPNG()) { return imageData.ToArray(); } } private IImageSourceHandler GetHandlerFor(ImageSource source) { IImageSourceHandler result; if (source is FileImageSource) result = new FileImageSourceHandler(); else if (source is StreamImageSource) result = new StreamImagesourceHandler(); else result = new ImageLoaderSourceHandler(); return result; } }
#Forms Note that I inserted [assembly: Dependecy(typeof(ImageLoader))] so we can use the Xamarin Forms to recognize and bring the correct ImageLoader from each Platform so we use it like this
byte[] bytes = await DependencyService.Get<IImageLoader>().LoadImageAsync(imgSource); string base64String = Convert.ToBase64String(bytes) //convert the binary to a string representation in base64
#note IImageLoaderis a simple interface like the following
public interface IImageLoader { Task<byte[]> LoadImageAsync(ImageSource source); }