从WebRequest流创建ImageBrush

时间:2015-05-08 21:22:29

标签: c# wpf stream imagebrush

我在ImageBrush创建Stream时遇到了困难。以下代码用于使用Rectangle填充WPF ImageBrush

        ImageBrush imgBrush = new ImageBrush();
        imgBrush.ImageSource = new BitmapImage(new Uri("\\image.png", UriKind.Relative));
        Rectangle1.Fill = imgBrush;

我想要做的是拨打WebRequest并获取Stream。然后我想用Stream图像填充我的矩形。这是代码:

        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;

问题在于我不知道如何使用imgBrush.ImageSource设置response.GetResponseStream()。如何在Stream中使用ImageBrush

1 个答案:

答案 0 :(得分:0)

BitmapImage constructors没有以Stream作为参数的重载 要使用响应流,您应该使用无参数构造函数并设置StreamSource属性。

看起来像这样:

// 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;