mpen
mpen

Reputation: 282855

Set System.Windows.Controls.Image from StreamReader?

I've got an image in PNG format in a StreamReader object. I want to display it on my WPF form. What's the easiest way to do that?

I've put an Image control on the form, but I don't know how to set it.

Upvotes: 1

Views: 2854

Answers (3)

mpen
mpen

Reputation: 282855

This seems to work:

 image1.Source = BitmapFrame.Create(myStreamReader.BaseStream);

Upvotes: 2

tofutim
tofutim

Reputation: 23374

Instead of using a StreamReader, I would directly generate the Stream,

FileStream strm = new FileStream("myImage.png", FileMode.Open);
PngBitmapDecoder decoder = new PngBitmapDecoder(strm,
    BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
myImage.Source = decoder.Frames[0];

where myImage is the name of your Image in XAML

<Image x:Name="myImage"/> 

Update: If you have to use the StreamReader, you get the Stream by using .BaseStream.

Upvotes: 0

ColinE
ColinE

Reputation: 70132

The Image.Source property requires that you supply a BitmapSource instance. To create this from a PNG you will need to decode it. See the related question here:

WPF BitmapSource ImageSource

BitmapSource source = null;

PngBitmapDecoder decoder;
using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

    if (decoder.Frames != null && decoder.Frames.Count > 0)
        source = decoder.Frames[0];
}

return source;

Upvotes: 2

Related Questions