Convert base64 string to image in C # on Windows Phone

I have a base64 string and I want to convert this to an image and set the original Image control to the result.

I usually did this with help Image.FromStream, similar to this:

Image img;
byte[] fileBytes = Convert.FromBase64String(imageString);
using(MemoryStream ms = new MemoryStream())
{
    ms.Write(fileBytes, 0, fileBytes.Length);
    img = Image.FromStream(ms);
}

However, the method Image.FromStream does not exist on Windows Phone , and a random search only displays results that depend on this method.

+5
source share
1 answer

You can use this method:

    public static BitmapImage base64image(string base64string)
    {
        byte[] fileBytes = Convert.FromBase64String(base64string);

        using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
        {
            ms.Write(fileBytes, 0, fileBytes.Length);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.SetSource(ms);
            return bitmapImage;
        }
    }

Add the image to your XAML, for example:

    <Image x:Name="myWonderfulImage" />

Then you can set the source, for example:

myWonderfulImage.Source = base64image(yourBase64string);
+11
source

All Articles