Convert base64 string to image in C# on Windows Phone

半城伤御伤魂 提交于 2019-12-17 14:18:03

问题


I have a base64 string and I want convert that to an image and set the Source of an Image control to the result of that.

Normally I would do that using 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 Image.FromStream method does not exist on Windows Phone, and a casual search only turns up results that depend on that method.


回答1:


You can use a method like this:

    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 an image to your XAML, such as this:

    <Image x:Name="myWonderfulImage" />

You can then set the source, like this:

myWonderfulImage.Source = base64image(yourBase64string);


来源:https://stackoverflow.com/questions/14539005/convert-base64-string-to-image-in-c-sharp-on-windows-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!