【问题标题】:Creating an ImageBrush from a WebRequest stream从 WebRequest 流创建 ImageBrush
【发布时间】:2015-05-08 21:22:28
【问题描述】:

我在从 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

【问题讨论】:

    标签: c# wpf stream imagebrush


    【解决方案1】:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      相关资源
      最近更新 更多