从WebRequest流创建ImageBrush



我很难从Stream创建我的ImageBrush。以下代码用于使用ImageBrush填充WPF Rectangle

        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;

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

BitmapImage构造函数没有超载以 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;

相关内容

  • 没有找到相关文章