Displaying Base64 encoded image in Xamarin.Forms

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.

Xamarin logo, soon to be Base64
Xamarin logo, soon to be Base64

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.

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.

And that’s it! The image should now display and it works across all platforms.

Image served!
Image served!

Bonus – UWP only

If you are building a UWP app, you have two alternative options for creating a BitmapImage from Base64 string:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

*