Cheese1223
Cheese1223

Reputation: 107

Read Base64 image with C# in a Windows 8 app

I'm trying to display an image on a Windows 8 app. The image data is gathered from a web service, and provided as a Base64 encoded string.

I found the following on Stack Overflow:

How do i read a base64 image in WPF?

However, when I come to use the BitmapImage Class, I can't seem to access System.Windows.Media.Imaging, even though the following Microsoft documentation leads us to believe that it is available for use in .NET 4.5, and with Windows 8 apps:

http://msdn.microsoft.com/en-us/library/ms619218.aspx

Many thanks for your help.

Upvotes: 1

Views: 2606

Answers (1)

JP Alioto
JP Alioto

Reputation: 45117

The classes you want are in the Windows.UI.Xaml.Media.Imaging namespace. Here is an example of taking a Base64 image and creating an image out of it ...

var img = @"/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQ ... "; // Full Base64 image as string here
var imgBytes = Convert.FromBase64String(img);
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBytes(imgBytes);
await dw.StoreAsync();
ms.Seek(0);

var bm = new BitmapImage();
bm.SetSource(ms);

// img1 is an Image Control in XAML
bm.ImageOpened += (s, e) => { this.img1.Source = bm; };
bm.ImageFailed += (s, e) => { Debug.WriteLine(e.ErrorMessage); };

I could not copy a full Base64 image into the answer.

Upvotes: 3

Related Questions