Skip to content

Instantly share code, notes, and snippets.

@nozzlegear
Last active December 19, 2015 12:39
Show Gist options
  • Save nozzlegear/9dbdf6a40464eb09fdab to your computer and use it in GitHub Desktop.
Save nozzlegear/9dbdf6a40464eb09fdab to your computer and use it in GitHub Desktop.
Loading an image from a Base64 string in Windows Phone and Windows 8
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556
namespace MyApp
{
public sealed partial class MyPage : Page
{
public MyPage()
{
this.InitializeComponent();
}
// # # #
// Other page logic here
// # # #
private string base64Url = "https://gist.githubusercontent.com/asyncwords/c9c5e956396327a2e605/raw/8cb72ef38241851607375aa7edda2dda504e4438/";
private bool gettingImage = false;
private async void ImageButton_Click(object sender, RoutedEventArgs e)
{
//Check the locking bool so we don't download images multiple times
if (!gettingImage)
{
gettingImage = true;
//Get the button and change it's text to let the user know what's happening
var button = sender as Button;
button.Content = "Getting New Image";
// TODO: Download or get your Base64 string. I'm using the base64 string located here:
// https://gist.githubusercontent.com/asyncwords/c9c5e956396327a2e605/raw/8cb72ef38241851607375aa7edda2dda504e4438/
string base64String = await DownloadImageAsBase64();
//xaml images cannot use a base64 string as their source. We'll need to create a bitmap image instead.
var bitmap = new BitmapImage();
//Bitmap images use a URI or a stream as their source, so let's convert our base64 string to a stream
using (var stream = new MemoryStream(Convert.FromBase64String(base64String)))
{
//We're using WinRT (Windows Phone or Windows 8 app) in this example. Bitmaps in WinRT use an IRandomAccessStream as their source
await bitmap.SetSourceAsync(stream.AsRandomAccessStream());
}
//Bitmap is ready, set it as our image's source
this.MyImage.Source = bitmap;
//Set the locking bool to false so the user can download another image
gettingImage = false;
//Reset button text
button.Content = "Get New Image";
}
}
private async Task<string> DownloadImageAsBase64()
{
//Create an httpclient and download the string
var client = new HttpClient();
var base64String = await client.GetStringAsync(new Uri(base64Url));
return base64String;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment