【发布时间】:2011-03-12 13:45:49
【问题描述】:
您好,我一直在寻找在列表框内的图像控件中显示图像的解决方案。我已经看到设置图像源并分配它new BitmapImage(new Uri(stringX))。
在我的情况下,我首先使用函数中的WebClient 从 URL 中检索所有图像,并且该函数在经过一些处理后返回 MemoryStream。
现在我要做的是显示该图像,因此我没有 Uri 来创建新位图。所以我尝试实现 StreamSource 但我得到了
Set property 'System.Windows.Media.Imaging.BitmapImage.StreamSource' threw an exception.
这是我的代码
从网络检索图像
public MemoryStream GetImage(string id)
{
WebResponse result = null;
Image rImage = null;
MemoryStream imageStream = null;
try
{
string url = "https://devnmark.com/" + id + "/picture";
WebRequest request = WebRequest.Create(url);
result = request.GetResponse();
Stream stream = result.GetResponseStream();
BinaryReader br = new BinaryReader(stream);
byte[] rBytes = br.ReadBytes(1000000);
br.Close();
result.Close();
imageStream = new MemoryStream(rBytes, 0, rBytes.Length);
imageStream.Write(rBytes, 0, rBytes.Length);
rImage = Image.FromStream(imageStream, true);
// imageStream.Close();
}
catch (Exception c)
{
//MessageBox.Show(c.Message);
}
finally
{
if (result != null) result.Close();
}
return imageStream;
}
为类型声明的类
class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsChecked { get; set; }
public MemoryStream Picture { get; set; }
}
加载图片
private void LoadFriends()
{
foreach (dynamic imge in MainList)
{
if (x >= 6)
break;
UserInfo info = new UserInfo();
info.Id = int.Parse(imge.id);
info.Name = imge.name;
info.Picture = function.GetImage(info.Id.ToString());
FriendList.Add(info);
x++;
}
list.ItemsSource = FriendList;
}
列表框的 XMAL
<ListBox x:Name="list" Margin="18,100,535,74" >
<ListBox.ItemTemplate>
<HierarchicalDataTemplate>
<StackPanel Orientation="Horizontal">
<Image Height="50" Width="50">
<Image.Source>
<BitmapImage StreamSource="Picture" ></BitmapImage>
</Image.Source>
</Image>
<my:RibbonCheckBox Label="{Binding Name}" IsChecked="{Binding IsChecked}" />
</StackPanel>
</HierarchicalDataTemplate>
</ListBox.ItemTemplate>
</ListBox>
【问题讨论】:
-
你介意告诉什么抛出的异常吗?
-
我有问题提到过
-
没有异常应该像
ArgumentOutOfRangeException、ObjectDisposedException或类似的。您还应该说明在哪一行引发了异常。
标签: c# wpf wpf-controls stream bitmap