C# 从WebRequest流创建ImageBrush
从C# 从WebRequest流创建ImageBrush,c#,wpf,stream,imagebrush,C#,Wpf,Stream,Imagebrush,从流创建图像笔刷时遇到困难。以下代码用于使用图像笔刷填充WPF矩形: ImageBrush imgBrush = new ImageBrush(); imgBrush.ImageSource = new BitmapImage(new Uri("\\image.png", UriKind.Relative)); Rectangle1.Fill = imgBrush; 我想做的是调用WebRequest并获取流。然后我想用流图像填充我的矩形。代码如
流创建图像笔刷
时遇到困难。以下代码用于使用图像笔刷填充WPF矩形
:
ImageBrush imgBrush = new ImageBrush();
imgBrush.ImageSource = new BitmapImage(new Uri("\\image.png", UriKind.Relative));
Rectangle1.Fill = imgBrush;
我想做的是调用WebRequest
并获取流。然后我想用流
图像填充我的矩形。代码如下:
ImageBrush imgBrush = new ImageBrush();
WebRequest request = WebRequest.Create(iconurl);
WebResponse response = request.GetResponse();
Stream s = response.GetResponseStream();
imgBrush.ImageSource = new BitmapImage(s); // Here is the problem
Rectangle1.Fill = imgBrush;
问题是我不知道如何使用response.GetResponseStream()
设置我的imgBrush.ImageSource
。如何在我的ImageBrush
中使用流
?没有将流
作为参数的重载。
要使用响应流,应该使用无参数构造函数并设置属性
它看起来是这样的:
// Get the stream for the image
WebRequest request = WebRequest.Create(iconurl);
WebResponse response = request.GetResponse();
Stream s = response.GetResponseStream();
// Load the stream into the image
BitmapImage image = new BitmapImage();
image.StreamSource = s;
// Apply image as source
ImageBrush imgBrush = new ImageBrush();
imgBrush.ImageSource = image;
// Fill the rectangle
Rectangle1.Fill = imgBrush;