0

I am having difficulties creating my ImageBrush from a Stream. The following code is used to fill a WPF Rectangle using an ImageBrush:

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

What I want to do is call a WebRequest and obtain a Stream. Then I want to fill my rectangle using the Stream image. Here is the code:

        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;

The problem is that I do not know how to set my imgBrush.ImageSource using response.GetResponseStream(). How can I consume a Stream in my ImageBrush?

Stefan Over
  • 5,851
  • 2
  • 35
  • 61

1 Answers1

0

The BitmapImage constructors don't have an overload taking a Stream as parameter.
To use the response stream, you should use the parameterless constructor and set the StreamSource property.

It would look like this:

// 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;
Stefan Over
  • 5,851
  • 2
  • 35
  • 61