Base64 encoding is quite often used to store binary data as strings, including images on the web. Working with Base64 is built-in to .NET so in this article we will try to decode a image and display it in a Xamarin.Forms app.
Sample image
As a sample image I have used a PNG version of the Xamarin logo. If you want to get its Base64 version, you can download it as part of the sample source code on GitHub.
Decoding
When it comes to converting "anything to anything", the System.Convert
class is usually the best start. There are four methods dealing with Base64:
ToBase64String
FromBase64String
ToBase64CharArray
FromBase64CharArray
We will use the
FromBase64String
method which you supply a Base64 encoded string and you will get a byte array in return.
var byteArray = Convert.FromBase64String(source);
Displaying the image
To be able to display an image, we need an instance of Xamarin.Forms.ImageSource
. We can create it from a Stream
and as we have the byte array in memory, a MemoryStream
is the natural best fit.
Stream stream = new MemoryStream(byteArray); var imageSource = ImageSource.FromStream(()=>stream); MyImage.Source = imageSource;
And that's it! The image should now display and it works across all platforms.
Bonus – UWP only
If you are building a UWP app, you have two alternative options for creating a BitmapImage
from Base64 string:
public async Task<BitmapImage> Base64StringToBitmapLongerAsync(string source) { var inMemoryStream = new InMemoryRandomAccessStream(); var byteArray = Convert.FromBase64String(source); var dataWriter = new DataWriter(inMemoryStream); dataWriter.WriteBytes(byteArray); await dataWriter.StoreAsync(); inMemoryStream.Seek(0); var bitmapImage = new BitmapImage(); bitmapImage.SetSourceAsync(inMemoryStream); return bitmapImage; } public async Task<BitmapImage> Base64StringToBitmapSimplerAsync(string source) { var byteArray = Convert.FromBase64String(source); BitmapImage bitmap = new BitmapImage(); using (MemoryStream stream = new MemoryStream(byteArray)) { await bitmap.SetSourceAsync(stream.AsRandomAccessStream()); } return bitmap; }
Both solutions work equally well, but utilize async/await
and SetSourceAsync
which is the recommended approach in UWP.
Sample code
Source code for this article is available on my GitHub.
Summary
We have shown how to decode a Base64 image and display it in a Xamarin.Forms app. We also shown alternative approaches for UWP using async
.