简体   繁体   中英

Displaying image from base64string

I'm displaying an image from a base 64 string that came from an API. The problem is, the image is not being displayed.

Here's the code:

profilePictureImg.Source = GetUserImage(user.MobileNumber);


private BitmapImage GetUserImage(string phoneNumber)
    {
        BitmapImage bitmapImage = new BitmapImage();

        var baseAddress = "http://192.168.0.103/vchatapi/api/Images/" + phoneNumber;

        var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
        http.Accept = "application/json";
        http.ContentType = "application/json";
        http.Method = "GET";

        var response = http.GetResponse();

        var stream = response.GetResponseStream();
        var sr = new StreamReader(stream);
        var content = sr.ReadToEnd();
        var y ="";
        var x = y.FromJson(content);

        byte[] binaryData = Convert.FromBase64String(x);

        using (MemoryStream ms = new MemoryStream(binaryData, 0, binaryData.Length))
        {
            ms.Write(binaryData, 0, binaryData.Length);
            bitmapImage.StreamSource = ms;

        }
        return bitmapImage;
    }

Any Ideas?? Thanks!

EDIT:

Got the fix. For some reason, it requires to call BeginInit and EndInit.

The image may be decoded as shown in this answer :

var binaryData = Convert.FromBase64String(x);
var bitmapImage = new BitmapImage();

using (var stream = new MemoryStream(binaryData))
{
    bitmapImage.BeginInit();
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = stream;
    bitmapImage.EndInit();
}

The reason why you have to use BeginInit and EndInit is explained in the Remarks section of the BitmapImage MSDN documentation :

BitmapImage implements the ISupportInitialize interface to optimize initialization on multiple properties. Property changes can only occur during object initialization. Call BeginInit to signal that initialization has begun and EndInit to signal that initialization has completed. After initialization, property changes are ignored.

This may be one of those cases where it pays not to dispose the stream too eagerly; also, the Write here is unnecessary: you already added the data via the constructor. So just:

bitmapImage.StreamSource = new MemoryStream(binaryData);
return bitmapImage;

does that work?

You can try the following

byte[] binaryData = Convert.FromBase64String(x);
using (MemoryStream ms = new MemoryStream(binaryData))
{
    bitmapImage = (Bitmap)Image.FromStream(ms);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM