我正在显示来自API的基本64字符串的图像。问题是,图像没有显示。
以下是代码:
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;
}
任何想法?谢谢!
编辑:
得到了修复。出于某种原因,它需要调用BeginInit和EndInit。
答案 0 :(得分:3)
可以按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();
}
BitmapImage MSDN documentation的备注部分解释了您必须使用BeginInit
和EndInit
的原因:
BitmapImage实现了ISupportInitialize接口以进行优化 初始化多个属性。财产变更只能发生 对象初始化期间。调用BeginInit来发出信号 初始化已经开始,EndInit表示初始化有 完成。初始化后,将忽略属性更改。
答案 1 :(得分:0)
这可能是支付而非过于急切地处理流的情况之一;另外,这里的Write
是不必要的:你已经通过构造函数添加了数据。所以只是:
bitmapImage.StreamSource = new MemoryStream(binaryData);
return bitmapImage;
有效吗?
答案 2 :(得分:0)
您可以尝试以下
byte[] binaryData = Convert.FromBase64String(x);
using (MemoryStream ms = new MemoryStream(binaryData))
{
bitmapImage = (Bitmap)Image.FromStream(ms);
}