开发者

Set System.Windows.Controls.Image from StreamReader?

开发者 https://www.devze.com 2023-03-08 04:02 出处:网络
I\'ve got an image in PNG fo开发者_JAVA百科rmat in a StreamReader object. I want to display it on my WPF form. What\'s the easiest way to do that?

I've got an image in PNG fo开发者_JAVA百科rmat 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.


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;


This seems to work:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消