C# 使用图像控制WPF
您好,我一直在寻找一种在列表框内的图像控件中显示图像的解决方案。我看到了如何设置图像源并为其分配C# 使用图像控制WPF,c#,wpf,wpf-controls,stream,bitmap,C#,Wpf,Wpf Controls,Stream,Bitmap,您好,我一直在寻找一种在列表框内的图像控件中显示图像的解决方案。我看到了如何设置图像源并为其分配新位图图像(新Uri(stringX)) 在我的情况下不是这样的,我首先使用WebClient从URL检索所有图像,该函数处于函数状态,经过一些处理后返回MemoryStream 现在我想做的是显示那个图像,这样我就没有Uri来创建新的位图了 Set property 'System.Windows.Media.Imaging.BitmapImage.StreamSource' threw an
新位图图像(新Uri(stringX))
在我的情况下不是这样的,我首先使用WebClient
从URL检索所有图像,该函数处于函数状态,经过一些处理后返回MemoryStream
现在我想做的是显示那个图像,这样我就没有Uri来创建新的位图了
Set property 'System.Windows.Media.Imaging.BitmapImage.StreamSource' threw an exception.
这是我的密码
从Web检索图像
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>
你有一大堆问题
byte[] rBytes = br.ReadBytes(1000000);
如果图像大于1MB怎么办
拆下线路
rImage = Image.FromStream(imageStream, true);
您不使用由此产生的结果,它只需要花费处理时间并将imageStream定位在末尾
在返回之前,您可能应该使用将流重置为其起始位置
imageStream.Seek(0, SeekOrigin.Begin);
编辑
您的XAML绑定错误
<BitmapImage StreamSource="Picture" ></BitmapImage>
应该是
<BitmapImage StreamSource="{Binding Picture}" ></BitmapImage>
是一个有效的绑定,但实际上我不确定是否可以绑定
StreamSource
,或者是否需要从代码进行初始化,就像下面的示例一样。据我所知,该网站似乎需要某种身份验证。
你提供了吗?
你能给我们一个有效的网址吗 你介意告诉我抛出了什么异常吗?我已经在问题中提到过了。否异常应该类似于
ArgumentOutOfRangeException
,ObjectDisposedException
或类似的异常。您还应该告诉异常是在哪一行引发的。仍然会提到异常above@Afnan,您还没有告诉任何人抛出了什么异常。异常标题=XmlParseException
,它读取Set属性“System.Windows.Media.Imaging.BitmapImage.StreamSource”引发了异常。@这可能是因为绑定声明不正确,我更新了我的答案。是的,这就是问题所在。谢谢你帮了我很多忙。问题不在网站上。如果给出了结果,如果我添加了断点,我会看到那里有一个位图图像